Driver.cpp 85 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324
  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 "InputInfo.h"
  11. #include "ToolChains.h"
  12. #include "clang/Basic/Version.h"
  13. #include "clang/Config/config.h"
  14. #include "clang/Driver/Action.h"
  15. #include "clang/Driver/Compilation.h"
  16. #include "clang/Driver/DriverDiagnostic.h"
  17. #include "clang/Driver/Job.h"
  18. #include "clang/Driver/Options.h"
  19. #include "clang/Driver/SanitizerArgs.h"
  20. #include "clang/Driver/Tool.h"
  21. #include "clang/Driver/ToolChain.h"
  22. #include "llvm/ADT/ArrayRef.h"
  23. #include "llvm/ADT/STLExtras.h"
  24. #include "llvm/ADT/StringExtras.h"
  25. #include "llvm/ADT/StringSet.h"
  26. #include "llvm/ADT/StringSwitch.h"
  27. #include "llvm/Option/Arg.h"
  28. #include "llvm/Option/ArgList.h"
  29. #include "llvm/Option/OptSpecifier.h"
  30. #include "llvm/Option/OptTable.h"
  31. #include "llvm/Option/Option.h"
  32. #include "llvm/Support/Debug.h"
  33. #include "llvm/Support/ErrorHandling.h"
  34. #include "llvm/Support/FileSystem.h"
  35. #include "llvm/Support/Path.h"
  36. #include "llvm/Support/PrettyStackTrace.h"
  37. #include "llvm/Support/Process.h"
  38. #include "llvm/Support/Program.h"
  39. #include "llvm/Support/raw_ostream.h"
  40. #include <map>
  41. #include <memory>
  42. using namespace clang::driver;
  43. using namespace clang;
  44. using namespace llvm::opt;
  45. Driver::Driver(StringRef ClangExecutable, StringRef DefaultTargetTriple,
  46. DiagnosticsEngine &Diags)
  47. : Opts(createDriverOptTable()), Diags(Diags), Mode(GCCMode),
  48. SaveTemps(SaveTempsNone), ClangExecutable(ClangExecutable),
  49. SysRoot(DEFAULT_SYSROOT), UseStdLib(true),
  50. DefaultTargetTriple(DefaultTargetTriple),
  51. DriverTitle("clang LLVM compiler"), CCPrintOptionsFilename(nullptr),
  52. CCPrintHeadersFilename(nullptr), CCLogDiagnosticsFilename(nullptr),
  53. CCCPrintBindings(false), CCPrintHeaders(false), CCLogDiagnostics(false),
  54. CCGenDiagnostics(false), CCCGenericGCCName(""), CheckInputsExist(true),
  55. CCCUsePCH(true), SuppressMissingInputWarning(false) {
  56. Name = llvm::sys::path::filename(ClangExecutable);
  57. Dir = llvm::sys::path::parent_path(ClangExecutable);
  58. // Compute the path to the resource directory.
  59. StringRef ClangResourceDir(CLANG_RESOURCE_DIR);
  60. SmallString<128> P(Dir);
  61. if (ClangResourceDir != "") {
  62. llvm::sys::path::append(P, ClangResourceDir);
  63. } else {
  64. StringRef ClangLibdirSuffix(CLANG_LIBDIR_SUFFIX);
  65. llvm::sys::path::append(P, "..", Twine("lib") + ClangLibdirSuffix, "clang",
  66. CLANG_VERSION_STRING);
  67. }
  68. ResourceDir = P.str();
  69. }
  70. Driver::~Driver() {
  71. delete Opts;
  72. llvm::DeleteContainerSeconds(ToolChains);
  73. }
  74. void Driver::ParseDriverMode(ArrayRef<const char *> Args) {
  75. const std::string OptName =
  76. getOpts().getOption(options::OPT_driver_mode).getPrefixedName();
  77. for (const char *ArgPtr : Args) {
  78. // Ingore nullptrs, they are response file's EOL markers
  79. if (ArgPtr == nullptr)
  80. continue;
  81. const StringRef Arg = ArgPtr;
  82. if (!Arg.startswith(OptName))
  83. continue;
  84. const StringRef Value = Arg.drop_front(OptName.size());
  85. const unsigned M = llvm::StringSwitch<unsigned>(Value)
  86. .Case("gcc", GCCMode)
  87. .Case("g++", GXXMode)
  88. .Case("cpp", CPPMode)
  89. .Case("cl", CLMode)
  90. .Default(~0U);
  91. if (M != ~0U)
  92. Mode = static_cast<DriverMode>(M);
  93. else
  94. Diag(diag::err_drv_unsupported_option_argument) << OptName << Value;
  95. }
  96. }
  97. InputArgList Driver::ParseArgStrings(ArrayRef<const char *> ArgStrings) {
  98. llvm::PrettyStackTraceString CrashInfo("Command line argument parsing");
  99. unsigned IncludedFlagsBitmask;
  100. unsigned ExcludedFlagsBitmask;
  101. std::tie(IncludedFlagsBitmask, ExcludedFlagsBitmask) =
  102. getIncludeExcludeOptionFlagMasks();
  103. unsigned MissingArgIndex, MissingArgCount;
  104. InputArgList Args =
  105. getOpts().ParseArgs(ArgStrings, MissingArgIndex, MissingArgCount,
  106. IncludedFlagsBitmask, ExcludedFlagsBitmask);
  107. // Check for missing argument error.
  108. if (MissingArgCount)
  109. Diag(clang::diag::err_drv_missing_argument)
  110. << Args.getArgString(MissingArgIndex) << MissingArgCount;
  111. // Check for unsupported options.
  112. for (const Arg *A : Args) {
  113. if (A->getOption().hasFlag(options::Unsupported)) {
  114. Diag(clang::diag::err_drv_unsupported_opt) << A->getAsString(Args);
  115. continue;
  116. }
  117. // Warn about -mcpu= without an argument.
  118. if (A->getOption().matches(options::OPT_mcpu_EQ) && A->containsValue("")) {
  119. Diag(clang::diag::warn_drv_empty_joined_argument) << A->getAsString(Args);
  120. }
  121. }
  122. for (const Arg *A : Args.filtered(options::OPT_UNKNOWN))
  123. Diags.Report(diag::err_drv_unknown_argument) << A->getAsString(Args);
  124. return Args;
  125. }
  126. // Determine which compilation mode we are in. We look for options which
  127. // affect the phase, starting with the earliest phases, and record which
  128. // option we used to determine the final phase.
  129. phases::ID Driver::getFinalPhase(const DerivedArgList &DAL,
  130. Arg **FinalPhaseArg) const {
  131. Arg *PhaseArg = nullptr;
  132. phases::ID FinalPhase;
  133. // -{E,EP,P,M,MM} only run the preprocessor.
  134. if (CCCIsCPP() || (PhaseArg = DAL.getLastArg(options::OPT_E)) ||
  135. (PhaseArg = DAL.getLastArg(options::OPT__SLASH_EP)) ||
  136. (PhaseArg = DAL.getLastArg(options::OPT_M, options::OPT_MM)) ||
  137. (PhaseArg = DAL.getLastArg(options::OPT__SLASH_P))) {
  138. FinalPhase = phases::Preprocess;
  139. // -{fsyntax-only,-analyze,emit-ast} only run up to the compiler.
  140. } else if ((PhaseArg = DAL.getLastArg(options::OPT_fsyntax_only)) ||
  141. (PhaseArg = DAL.getLastArg(options::OPT_module_file_info)) ||
  142. (PhaseArg = DAL.getLastArg(options::OPT_verify_pch)) ||
  143. (PhaseArg = DAL.getLastArg(options::OPT_rewrite_objc)) ||
  144. (PhaseArg = DAL.getLastArg(options::OPT_rewrite_legacy_objc)) ||
  145. (PhaseArg = DAL.getLastArg(options::OPT__migrate)) ||
  146. (PhaseArg = DAL.getLastArg(options::OPT__analyze,
  147. options::OPT__analyze_auto)) ||
  148. (PhaseArg = DAL.getLastArg(options::OPT_emit_ast))) {
  149. FinalPhase = phases::Compile;
  150. // -S only runs up to the backend.
  151. } else if ((PhaseArg = DAL.getLastArg(options::OPT_S))) {
  152. FinalPhase = phases::Backend;
  153. // -c and partial CUDA compilations only run up to the assembler.
  154. } else if ((PhaseArg = DAL.getLastArg(options::OPT_c)) ||
  155. (PhaseArg = DAL.getLastArg(options::OPT_cuda_device_only)) ||
  156. (PhaseArg = DAL.getLastArg(options::OPT_cuda_host_only))) {
  157. FinalPhase = phases::Assemble;
  158. // Otherwise do everything.
  159. } else
  160. FinalPhase = phases::Link;
  161. if (FinalPhaseArg)
  162. *FinalPhaseArg = PhaseArg;
  163. return FinalPhase;
  164. }
  165. static Arg *MakeInputArg(DerivedArgList &Args, OptTable *Opts,
  166. StringRef Value) {
  167. Arg *A = new Arg(Opts->getOption(options::OPT_INPUT), Value,
  168. Args.getBaseArgs().MakeIndex(Value), Value.data());
  169. Args.AddSynthesizedArg(A);
  170. A->claim();
  171. return A;
  172. }
  173. DerivedArgList *Driver::TranslateInputArgs(const InputArgList &Args) const {
  174. DerivedArgList *DAL = new DerivedArgList(Args);
  175. bool HasNostdlib = Args.hasArg(options::OPT_nostdlib);
  176. for (Arg *A : Args) {
  177. // Unfortunately, we have to parse some forwarding options (-Xassembler,
  178. // -Xlinker, -Xpreprocessor) because we either integrate their functionality
  179. // (assembler and preprocessor), or bypass a previous driver ('collect2').
  180. // Rewrite linker options, to replace --no-demangle with a custom internal
  181. // option.
  182. if ((A->getOption().matches(options::OPT_Wl_COMMA) ||
  183. A->getOption().matches(options::OPT_Xlinker)) &&
  184. A->containsValue("--no-demangle")) {
  185. // Add the rewritten no-demangle argument.
  186. DAL->AddFlagArg(A, Opts->getOption(options::OPT_Z_Xlinker__no_demangle));
  187. // Add the remaining values as Xlinker arguments.
  188. for (const StringRef Val : A->getValues())
  189. if (Val != "--no-demangle")
  190. DAL->AddSeparateArg(A, Opts->getOption(options::OPT_Xlinker), Val);
  191. continue;
  192. }
  193. // Rewrite preprocessor options, to replace -Wp,-MD,FOO which is used by
  194. // some build systems. We don't try to be complete here because we don't
  195. // care to encourage this usage model.
  196. if (A->getOption().matches(options::OPT_Wp_COMMA) &&
  197. (A->getValue(0) == StringRef("-MD") ||
  198. A->getValue(0) == StringRef("-MMD"))) {
  199. // Rewrite to -MD/-MMD along with -MF.
  200. if (A->getValue(0) == StringRef("-MD"))
  201. DAL->AddFlagArg(A, Opts->getOption(options::OPT_MD));
  202. else
  203. DAL->AddFlagArg(A, Opts->getOption(options::OPT_MMD));
  204. if (A->getNumValues() == 2)
  205. DAL->AddSeparateArg(A, Opts->getOption(options::OPT_MF),
  206. A->getValue(1));
  207. continue;
  208. }
  209. // Rewrite reserved library names.
  210. if (A->getOption().matches(options::OPT_l)) {
  211. StringRef Value = A->getValue();
  212. // Rewrite unless -nostdlib is present.
  213. if (!HasNostdlib && Value == "stdc++") {
  214. DAL->AddFlagArg(A, Opts->getOption(options::OPT_Z_reserved_lib_stdcxx));
  215. continue;
  216. }
  217. // Rewrite unconditionally.
  218. if (Value == "cc_kext") {
  219. DAL->AddFlagArg(A, Opts->getOption(options::OPT_Z_reserved_lib_cckext));
  220. continue;
  221. }
  222. }
  223. // Pick up inputs via the -- option.
  224. if (A->getOption().matches(options::OPT__DASH_DASH)) {
  225. A->claim();
  226. for (const StringRef Val : A->getValues())
  227. DAL->append(MakeInputArg(*DAL, Opts, Val));
  228. continue;
  229. }
  230. DAL->append(A);
  231. }
  232. // Add a default value of -mlinker-version=, if one was given and the user
  233. // didn't specify one.
  234. #if defined(HOST_LINK_VERSION)
  235. if (!Args.hasArg(options::OPT_mlinker_version_EQ) &&
  236. strlen(HOST_LINK_VERSION) > 0) {
  237. DAL->AddJoinedArg(0, Opts->getOption(options::OPT_mlinker_version_EQ),
  238. HOST_LINK_VERSION);
  239. DAL->getLastArg(options::OPT_mlinker_version_EQ)->claim();
  240. }
  241. #endif
  242. return DAL;
  243. }
  244. /// \brief Compute target triple from args.
  245. ///
  246. /// This routine provides the logic to compute a target triple from various
  247. /// args passed to the driver and the default triple string.
  248. static llvm::Triple computeTargetTriple(StringRef DefaultTargetTriple,
  249. const ArgList &Args,
  250. StringRef DarwinArchName = "") {
  251. // FIXME: Already done in Compilation *Driver::BuildCompilation
  252. if (const Arg *A = Args.getLastArg(options::OPT_target))
  253. DefaultTargetTriple = A->getValue();
  254. llvm::Triple Target(llvm::Triple::normalize(DefaultTargetTriple));
  255. // Handle Apple-specific options available here.
  256. if (Target.isOSBinFormatMachO()) {
  257. // If an explict Darwin arch name is given, that trumps all.
  258. if (!DarwinArchName.empty()) {
  259. tools::darwin::setTripleTypeForMachOArchName(Target, DarwinArchName);
  260. return Target;
  261. }
  262. // Handle the Darwin '-arch' flag.
  263. if (Arg *A = Args.getLastArg(options::OPT_arch)) {
  264. StringRef ArchName = A->getValue();
  265. tools::darwin::setTripleTypeForMachOArchName(Target, ArchName);
  266. }
  267. }
  268. // Handle pseudo-target flags '-mlittle-endian'/'-EL' and
  269. // '-mbig-endian'/'-EB'.
  270. if (Arg *A = Args.getLastArg(options::OPT_mlittle_endian,
  271. options::OPT_mbig_endian)) {
  272. if (A->getOption().matches(options::OPT_mlittle_endian)) {
  273. llvm::Triple LE = Target.getLittleEndianArchVariant();
  274. if (LE.getArch() != llvm::Triple::UnknownArch)
  275. Target = std::move(LE);
  276. } else {
  277. llvm::Triple BE = Target.getBigEndianArchVariant();
  278. if (BE.getArch() != llvm::Triple::UnknownArch)
  279. Target = std::move(BE);
  280. }
  281. }
  282. // Skip further flag support on OSes which don't support '-m32' or '-m64'.
  283. if (Target.getArchName() == "tce" || Target.getOS() == llvm::Triple::Minix)
  284. return Target;
  285. // Handle pseudo-target flags '-m64', '-mx32', '-m32' and '-m16'.
  286. if (Arg *A = Args.getLastArg(options::OPT_m64, options::OPT_mx32,
  287. options::OPT_m32, options::OPT_m16)) {
  288. llvm::Triple::ArchType AT = llvm::Triple::UnknownArch;
  289. if (A->getOption().matches(options::OPT_m64)) {
  290. AT = Target.get64BitArchVariant().getArch();
  291. if (Target.getEnvironment() == llvm::Triple::GNUX32)
  292. Target.setEnvironment(llvm::Triple::GNU);
  293. } else if (A->getOption().matches(options::OPT_mx32) &&
  294. Target.get64BitArchVariant().getArch() == llvm::Triple::x86_64) {
  295. AT = llvm::Triple::x86_64;
  296. Target.setEnvironment(llvm::Triple::GNUX32);
  297. } else if (A->getOption().matches(options::OPT_m32)) {
  298. AT = Target.get32BitArchVariant().getArch();
  299. if (Target.getEnvironment() == llvm::Triple::GNUX32)
  300. Target.setEnvironment(llvm::Triple::GNU);
  301. } else if (A->getOption().matches(options::OPT_m16) &&
  302. Target.get32BitArchVariant().getArch() == llvm::Triple::x86) {
  303. AT = llvm::Triple::x86;
  304. Target.setEnvironment(llvm::Triple::CODE16);
  305. }
  306. if (AT != llvm::Triple::UnknownArch && AT != Target.getArch())
  307. Target.setArch(AT);
  308. }
  309. return Target;
  310. }
  311. Compilation *Driver::BuildCompilation(ArrayRef<const char *> ArgList) {
  312. llvm::PrettyStackTraceString CrashInfo("Compilation construction");
  313. // FIXME: Handle environment options which affect driver behavior, somewhere
  314. // (client?). GCC_EXEC_PREFIX, LPATH, CC_PRINT_OPTIONS.
  315. #if 0 // HLSL Change - disallow COMPILER_PATH environment setting
  316. if (char *env = ::getenv("COMPILER_PATH")) {
  317. StringRef CompilerPath = env;
  318. while (!CompilerPath.empty()) {
  319. std::pair<StringRef, StringRef> Split =
  320. CompilerPath.split(llvm::sys::EnvPathSeparator);
  321. PrefixDirs.push_back(Split.first);
  322. CompilerPath = Split.second;
  323. }
  324. }
  325. #endif // HLSL Change
  326. // We look for the driver mode option early, because the mode can affect
  327. // how other options are parsed.
  328. ParseDriverMode(ArgList.slice(1));
  329. // FIXME: What are we going to do with -V and -b?
  330. // FIXME: This stuff needs to go into the Compilation, not the driver.
  331. bool CCCPrintPhases;
  332. InputArgList Args = ParseArgStrings(ArgList.slice(1));
  333. // -no-canonical-prefixes is used very early in main.
  334. Args.ClaimAllArgs(options::OPT_no_canonical_prefixes);
  335. // Ignore -pipe.
  336. Args.ClaimAllArgs(options::OPT_pipe);
  337. // Extract -ccc args.
  338. //
  339. // FIXME: We need to figure out where this behavior should live. Most of it
  340. // should be outside in the client; the parts that aren't should have proper
  341. // options, either by introducing new ones or by overloading gcc ones like -V
  342. // or -b.
  343. CCCPrintPhases = Args.hasArg(options::OPT_ccc_print_phases);
  344. CCCPrintBindings = Args.hasArg(options::OPT_ccc_print_bindings);
  345. if (const Arg *A = Args.getLastArg(options::OPT_ccc_gcc_name))
  346. CCCGenericGCCName = A->getValue();
  347. CCCUsePCH =
  348. Args.hasFlag(options::OPT_ccc_pch_is_pch, options::OPT_ccc_pch_is_pth);
  349. // FIXME: DefaultTargetTriple is used by the target-prefixed calls to as/ld
  350. // and getToolChain is const.
  351. if (IsCLMode()) {
  352. // clang-cl targets MSVC-style Win32.
  353. llvm::Triple T(DefaultTargetTriple);
  354. T.setOS(llvm::Triple::Win32);
  355. T.setEnvironment(llvm::Triple::MSVC);
  356. DefaultTargetTriple = T.str();
  357. }
  358. if (const Arg *A = Args.getLastArg(options::OPT_target))
  359. DefaultTargetTriple = A->getValue();
  360. if (const Arg *A = Args.getLastArg(options::OPT_ccc_install_dir))
  361. Dir = InstalledDir = A->getValue();
  362. for (const Arg *A : Args.filtered(options::OPT_B)) {
  363. A->claim();
  364. PrefixDirs.push_back(A->getValue(0));
  365. }
  366. if (const Arg *A = Args.getLastArg(options::OPT__sysroot_EQ))
  367. SysRoot = A->getValue();
  368. if (const Arg *A = Args.getLastArg(options::OPT__dyld_prefix_EQ))
  369. DyldPrefix = A->getValue();
  370. if (Args.hasArg(options::OPT_nostdlib))
  371. UseStdLib = false;
  372. if (const Arg *A = Args.getLastArg(options::OPT_resource_dir))
  373. ResourceDir = A->getValue();
  374. if (const Arg *A = Args.getLastArg(options::OPT_save_temps_EQ)) {
  375. SaveTemps = llvm::StringSwitch<SaveTempsMode>(A->getValue())
  376. .Case("cwd", SaveTempsCwd)
  377. .Case("obj", SaveTempsObj)
  378. .Default(SaveTempsCwd);
  379. }
  380. std::unique_ptr<llvm::opt::InputArgList> UArgs =
  381. llvm::make_unique<InputArgList>(std::move(Args));
  382. // Perform the default argument translations.
  383. DerivedArgList *TranslatedArgs = TranslateInputArgs(*UArgs);
  384. // Owned by the host.
  385. const ToolChain &TC =
  386. getToolChain(*UArgs, computeTargetTriple(DefaultTargetTriple, *UArgs));
  387. // The compilation takes ownership of Args.
  388. Compilation *C = new Compilation(*this, TC, UArgs.release(), TranslatedArgs);
  389. if (!HandleImmediateArgs(*C))
  390. return C;
  391. // Construct the list of inputs.
  392. InputList Inputs;
  393. BuildInputs(C->getDefaultToolChain(), *TranslatedArgs, Inputs);
  394. // Construct the list of abstract actions to perform for this compilation. On
  395. // MachO targets this uses the driver-driver and universal actions.
  396. if (TC.getTriple().isOSBinFormatMachO())
  397. BuildUniversalActions(C->getDefaultToolChain(), C->getArgs(), Inputs,
  398. C->getActions());
  399. else
  400. BuildActions(C->getDefaultToolChain(), C->getArgs(), Inputs,
  401. C->getActions());
  402. if (CCCPrintPhases) {
  403. PrintActions(*C);
  404. return C;
  405. }
  406. BuildJobs(*C);
  407. return C;
  408. }
  409. static void printArgList(raw_ostream &OS, const llvm::opt::ArgList &Args) {
  410. llvm::opt::ArgStringList ASL;
  411. for (const auto *A : Args)
  412. A->render(Args, ASL);
  413. for (auto I = ASL.begin(), E = ASL.end(); I != E; ++I) {
  414. if (I != ASL.begin())
  415. OS << ' ';
  416. Command::printArg(OS, *I, true);
  417. }
  418. OS << '\n';
  419. }
  420. // When clang crashes, produce diagnostic information including the fully
  421. // preprocessed source file(s). Request that the developer attach the
  422. // diagnostic information to a bug report.
  423. void Driver::generateCompilationDiagnostics(Compilation &C,
  424. const Command &FailingCommand) {
  425. if (C.getArgs().hasArg(options::OPT_fno_crash_diagnostics))
  426. return;
  427. // Don't try to generate diagnostics for link or dsymutil jobs.
  428. if (FailingCommand.getCreator().isLinkJob() ||
  429. FailingCommand.getCreator().isDsymutilJob())
  430. return;
  431. // Print the version of the compiler.
  432. PrintVersion(C, llvm::errs());
  433. Diag(clang::diag::note_drv_command_failed_diag_msg)
  434. << "PLEASE submit a bug report to " BUG_REPORT_URL " and include the "
  435. "crash backtrace, preprocessed source, and associated run script.";
  436. // Suppress driver output and emit preprocessor output to temp file.
  437. Mode = CPPMode;
  438. CCGenDiagnostics = true;
  439. // Save the original job command(s).
  440. Command Cmd = FailingCommand;
  441. // Keep track of whether we produce any errors while trying to produce
  442. // preprocessed sources.
  443. DiagnosticErrorTrap Trap(Diags);
  444. // Suppress tool output.
  445. C.initCompilationForDiagnostics();
  446. // Construct the list of inputs.
  447. InputList Inputs;
  448. BuildInputs(C.getDefaultToolChain(), C.getArgs(), Inputs);
  449. for (InputList::iterator it = Inputs.begin(), ie = Inputs.end(); it != ie;) {
  450. bool IgnoreInput = false;
  451. // Ignore input from stdin or any inputs that cannot be preprocessed.
  452. // Check type first as not all linker inputs have a value.
  453. if (types::getPreprocessedType(it->first) == types::TY_INVALID) {
  454. IgnoreInput = true;
  455. } else if (!strcmp(it->second->getValue(), "-")) {
  456. Diag(clang::diag::note_drv_command_failed_diag_msg)
  457. << "Error generating preprocessed source(s) - "
  458. "ignoring input from stdin.";
  459. IgnoreInput = true;
  460. }
  461. if (IgnoreInput) {
  462. it = Inputs.erase(it);
  463. ie = Inputs.end();
  464. } else {
  465. ++it;
  466. }
  467. }
  468. if (Inputs.empty()) {
  469. Diag(clang::diag::note_drv_command_failed_diag_msg)
  470. << "Error generating preprocessed source(s) - "
  471. "no preprocessable inputs.";
  472. return;
  473. }
  474. // Don't attempt to generate preprocessed files if multiple -arch options are
  475. // used, unless they're all duplicates.
  476. llvm::StringSet<> ArchNames;
  477. for (const Arg *A : C.getArgs()) {
  478. if (A->getOption().matches(options::OPT_arch)) {
  479. StringRef ArchName = A->getValue();
  480. ArchNames.insert(ArchName);
  481. }
  482. }
  483. if (ArchNames.size() > 1) {
  484. Diag(clang::diag::note_drv_command_failed_diag_msg)
  485. << "Error generating preprocessed source(s) - cannot generate "
  486. "preprocessed source with multiple -arch options.";
  487. return;
  488. }
  489. // Construct the list of abstract actions to perform for this compilation. On
  490. // Darwin OSes this uses the driver-driver and builds universal actions.
  491. const ToolChain &TC = C.getDefaultToolChain();
  492. if (TC.getTriple().isOSBinFormatMachO())
  493. BuildUniversalActions(TC, C.getArgs(), Inputs, C.getActions());
  494. else
  495. BuildActions(TC, C.getArgs(), Inputs, C.getActions());
  496. BuildJobs(C);
  497. // If there were errors building the compilation, quit now.
  498. if (Trap.hasErrorOccurred()) {
  499. Diag(clang::diag::note_drv_command_failed_diag_msg)
  500. << "Error generating preprocessed source(s).";
  501. return;
  502. }
  503. // Generate preprocessed output.
  504. SmallVector<std::pair<int, const Command *>, 4> FailingCommands;
  505. C.ExecuteJobs(C.getJobs(), FailingCommands);
  506. // If any of the preprocessing commands failed, clean up and exit.
  507. if (!FailingCommands.empty()) {
  508. if (!isSaveTempsEnabled())
  509. C.CleanupFileList(C.getTempFiles(), true);
  510. Diag(clang::diag::note_drv_command_failed_diag_msg)
  511. << "Error generating preprocessed source(s).";
  512. return;
  513. }
  514. const ArgStringList &TempFiles = C.getTempFiles();
  515. if (TempFiles.empty()) {
  516. Diag(clang::diag::note_drv_command_failed_diag_msg)
  517. << "Error generating preprocessed source(s).";
  518. return;
  519. }
  520. Diag(clang::diag::note_drv_command_failed_diag_msg)
  521. << "\n********************\n\n"
  522. "PLEASE ATTACH THE FOLLOWING FILES TO THE BUG REPORT:\n"
  523. "Preprocessed source(s) and associated run script(s) are located at:";
  524. SmallString<128> VFS;
  525. for (const char *TempFile : TempFiles) {
  526. Diag(clang::diag::note_drv_command_failed_diag_msg) << TempFile;
  527. if (StringRef(TempFile).endswith(".cache")) {
  528. // In some cases (modules) we'll dump extra data to help with reproducing
  529. // the crash into a directory next to the output.
  530. VFS = llvm::sys::path::filename(TempFile);
  531. llvm::sys::path::append(VFS, "vfs", "vfs.yaml");
  532. }
  533. }
  534. // Assume associated files are based off of the first temporary file.
  535. CrashReportInfo CrashInfo(TempFiles[0], VFS);
  536. std::string Script = CrashInfo.Filename.rsplit('.').first.str() + ".sh";
  537. std::error_code EC;
  538. llvm::raw_fd_ostream ScriptOS(Script, EC, llvm::sys::fs::F_Excl);
  539. if (EC) {
  540. Diag(clang::diag::note_drv_command_failed_diag_msg)
  541. << "Error generating run script: " + Script + " " + EC.message();
  542. } else {
  543. ScriptOS << "# Crash reproducer for " << getClangFullVersion() << "\n"
  544. << "# Driver args: ";
  545. printArgList(ScriptOS, C.getInputArgs());
  546. ScriptOS << "# Original command: ";
  547. Cmd.Print(ScriptOS, "\n", /*Quote=*/true);
  548. Cmd.Print(ScriptOS, "\n", /*Quote=*/true, &CrashInfo);
  549. Diag(clang::diag::note_drv_command_failed_diag_msg) << Script;
  550. }
  551. for (const auto &A : C.getArgs().filtered(options::OPT_frewrite_map_file,
  552. options::OPT_frewrite_map_file_EQ))
  553. Diag(clang::diag::note_drv_command_failed_diag_msg) << A->getValue();
  554. Diag(clang::diag::note_drv_command_failed_diag_msg)
  555. << "\n\n********************";
  556. }
  557. void Driver::setUpResponseFiles(Compilation &C, Command &Cmd) {
  558. #ifdef MSFT_SUPPORTS_CHILD_PROCESSES // HLSL Change
  559. // Since argumentsFitWithinSystemLimits() may underestimate system's capacity
  560. // if the tool does not support response files, there is a chance/ that things
  561. // will just work without a response file, so we silently just skip it.
  562. if (Cmd.getCreator().getResponseFilesSupport() == Tool::RF_None ||
  563. llvm::sys::argumentsFitWithinSystemLimits(Cmd.getArguments()))
  564. return;
  565. std::string TmpName = GetTemporaryPath("response", "txt");
  566. Cmd.setResponseFile(
  567. C.addTempFile(C.getArgs().MakeArgString(TmpName.c_str())));
  568. #endif
  569. }
  570. int Driver::ExecuteCompilation(
  571. Compilation &C,
  572. SmallVectorImpl<std::pair<int, const Command *>> &FailingCommands) {
  573. // Just print if -### was present.
  574. if (C.getArgs().hasArg(options::OPT__HASH_HASH_HASH)) {
  575. C.getJobs().Print(llvm::errs(), "\n", true);
  576. return 0;
  577. }
  578. // If there were errors building the compilation, quit now.
  579. if (Diags.hasErrorOccurred())
  580. return 1;
  581. // Set up response file names for each command, if necessary
  582. for (auto &Job : C.getJobs())
  583. setUpResponseFiles(C, Job);
  584. C.ExecuteJobs(C.getJobs(), FailingCommands);
  585. // Remove temp files.
  586. C.CleanupFileList(C.getTempFiles());
  587. // If the command succeeded, we are done.
  588. if (FailingCommands.empty())
  589. return 0;
  590. // Otherwise, remove result files and print extra information about abnormal
  591. // failures.
  592. for (const auto &CmdPair : FailingCommands) {
  593. int Res = CmdPair.first;
  594. const Command *FailingCommand = CmdPair.second;
  595. // Remove result files if we're not saving temps.
  596. if (!isSaveTempsEnabled()) {
  597. const JobAction *JA = cast<JobAction>(&FailingCommand->getSource());
  598. C.CleanupFileMap(C.getResultFiles(), JA, true);
  599. // Failure result files are valid unless we crashed.
  600. if (Res < 0)
  601. C.CleanupFileMap(C.getFailureResultFiles(), JA, true);
  602. }
  603. // Print extra information about abnormal failures, if possible.
  604. //
  605. // This is ad-hoc, but we don't want to be excessively noisy. If the result
  606. // status was 1, assume the command failed normally. In particular, if it
  607. // was the compiler then assume it gave a reasonable error code. Failures
  608. // in other tools are less common, and they generally have worse
  609. // diagnostics, so always print the diagnostic there.
  610. const Tool &FailingTool = FailingCommand->getCreator();
  611. if (!FailingCommand->getCreator().hasGoodDiagnostics() || Res != 1) {
  612. // FIXME: See FIXME above regarding result code interpretation.
  613. if (Res < 0)
  614. Diag(clang::diag::err_drv_command_signalled)
  615. << FailingTool.getShortName();
  616. else
  617. Diag(clang::diag::err_drv_command_failed) << FailingTool.getShortName()
  618. << Res;
  619. }
  620. }
  621. return 0;
  622. }
  623. void Driver::PrintHelp(bool ShowHidden) const {
  624. unsigned IncludedFlagsBitmask;
  625. unsigned ExcludedFlagsBitmask;
  626. std::tie(IncludedFlagsBitmask, ExcludedFlagsBitmask) =
  627. getIncludeExcludeOptionFlagMasks();
  628. ExcludedFlagsBitmask |= options::NoDriverOption;
  629. if (!ShowHidden)
  630. ExcludedFlagsBitmask |= HelpHidden;
  631. getOpts().PrintHelp(llvm::outs(), Name.c_str(), DriverTitle.c_str(),
  632. IncludedFlagsBitmask, ExcludedFlagsBitmask);
  633. }
  634. void Driver::PrintVersion(const Compilation &C, raw_ostream &OS) const {
  635. // FIXME: The following handlers should use a callback mechanism, we don't
  636. // know what the client would like to do.
  637. OS << getClangFullVersion() << '\n';
  638. const ToolChain &TC = C.getDefaultToolChain();
  639. OS << "Target: " << TC.getTripleString() << '\n';
  640. // Print the threading model.
  641. if (Arg *A = C.getArgs().getLastArg(options::OPT_mthread_model)) {
  642. // Don't print if the ToolChain would have barfed on it already
  643. if (TC.isThreadModelSupported(A->getValue()))
  644. OS << "Thread model: " << A->getValue();
  645. } else
  646. OS << "Thread model: " << TC.getThreadModel();
  647. OS << '\n';
  648. }
  649. /// PrintDiagnosticCategories - Implement the --print-diagnostic-categories
  650. /// option.
  651. static void PrintDiagnosticCategories(raw_ostream &OS) {
  652. // Skip the empty category.
  653. for (unsigned i = 1, max = DiagnosticIDs::getNumberOfCategories(); i != max;
  654. ++i)
  655. OS << i << ',' << DiagnosticIDs::getCategoryNameFromID(i) << '\n';
  656. }
  657. bool Driver::HandleImmediateArgs(const Compilation &C) {
  658. // The order these options are handled in gcc is all over the place, but we
  659. // don't expect inconsistencies w.r.t. that to matter in practice.
  660. if (C.getArgs().hasArg(options::OPT_dumpmachine)) {
  661. llvm::outs() << C.getDefaultToolChain().getTripleString() << '\n';
  662. return false;
  663. }
  664. if (C.getArgs().hasArg(options::OPT_dumpversion)) {
  665. // Since -dumpversion is only implemented for pedantic GCC compatibility, we
  666. // return an answer which matches our definition of __VERSION__.
  667. //
  668. // If we want to return a more correct answer some day, then we should
  669. // introduce a non-pedantically GCC compatible mode to Clang in which we
  670. // provide sensible definitions for -dumpversion, __VERSION__, etc.
  671. llvm::outs() << "4.2.1\n";
  672. return false;
  673. }
  674. if (C.getArgs().hasArg(options::OPT__print_diagnostic_categories)) {
  675. PrintDiagnosticCategories(llvm::outs());
  676. return false;
  677. }
  678. if (C.getArgs().hasArg(options::OPT_help) ||
  679. C.getArgs().hasArg(options::OPT__help_hidden)) {
  680. PrintHelp(C.getArgs().hasArg(options::OPT__help_hidden));
  681. return false;
  682. }
  683. if (C.getArgs().hasArg(options::OPT__version)) {
  684. // Follow gcc behavior and use stdout for --version and stderr for -v.
  685. PrintVersion(C, llvm::outs());
  686. return false;
  687. }
  688. if (C.getArgs().hasArg(options::OPT_v) ||
  689. C.getArgs().hasArg(options::OPT__HASH_HASH_HASH)) {
  690. PrintVersion(C, llvm::errs());
  691. SuppressMissingInputWarning = true;
  692. }
  693. const ToolChain &TC = C.getDefaultToolChain();
  694. if (C.getArgs().hasArg(options::OPT_v))
  695. TC.printVerboseInfo(llvm::errs());
  696. if (C.getArgs().hasArg(options::OPT_print_search_dirs)) {
  697. llvm::outs() << "programs: =";
  698. bool separator = false;
  699. for (const std::string &Path : TC.getProgramPaths()) {
  700. if (separator)
  701. llvm::outs() << ':';
  702. llvm::outs() << Path;
  703. separator = true;
  704. }
  705. llvm::outs() << "\n";
  706. llvm::outs() << "libraries: =" << ResourceDir;
  707. StringRef sysroot = C.getSysRoot();
  708. for (const std::string &Path : TC.getFilePaths()) {
  709. // Always print a separator. ResourceDir was the first item shown.
  710. llvm::outs() << ':';
  711. // Interpretation of leading '=' is needed only for NetBSD.
  712. if (Path[0] == '=')
  713. llvm::outs() << sysroot << Path.substr(1);
  714. else
  715. llvm::outs() << Path;
  716. }
  717. llvm::outs() << "\n";
  718. return false;
  719. }
  720. // FIXME: The following handlers should use a callback mechanism, we don't
  721. // know what the client would like to do.
  722. if (Arg *A = C.getArgs().getLastArg(options::OPT_print_file_name_EQ)) {
  723. llvm::outs() << GetFilePath(A->getValue(), TC) << "\n";
  724. return false;
  725. }
  726. if (Arg *A = C.getArgs().getLastArg(options::OPT_print_prog_name_EQ)) {
  727. llvm::outs() << GetProgramPath(A->getValue(), TC) << "\n";
  728. return false;
  729. }
  730. if (C.getArgs().hasArg(options::OPT_print_libgcc_file_name)) {
  731. llvm::outs() << GetFilePath("libgcc.a", TC) << "\n";
  732. return false;
  733. }
  734. if (C.getArgs().hasArg(options::OPT_print_multi_lib)) {
  735. for (const Multilib &Multilib : TC.getMultilibs())
  736. llvm::outs() << Multilib << "\n";
  737. return false;
  738. }
  739. if (C.getArgs().hasArg(options::OPT_print_multi_directory)) {
  740. for (const Multilib &Multilib : TC.getMultilibs()) {
  741. if (Multilib.gccSuffix().empty())
  742. llvm::outs() << ".\n";
  743. else {
  744. StringRef Suffix(Multilib.gccSuffix());
  745. assert(Suffix.front() == '/');
  746. llvm::outs() << Suffix.substr(1) << "\n";
  747. }
  748. }
  749. return false;
  750. }
  751. return true;
  752. }
  753. // Display an action graph human-readably. Action A is the "sink" node
  754. // and latest-occuring action. Traversal is in pre-order, visiting the
  755. // inputs to each action before printing the action itself.
  756. static unsigned PrintActions1(const Compilation &C, Action *A,
  757. std::map<Action *, unsigned> &Ids) {
  758. if (Ids.count(A)) // A was already visited.
  759. return Ids[A];
  760. std::string str;
  761. llvm::raw_string_ostream os(str);
  762. os << Action::getClassName(A->getKind()) << ", ";
  763. if (InputAction *IA = dyn_cast<InputAction>(A)) {
  764. os << "\"" << IA->getInputArg().getValue() << "\"";
  765. } else if (BindArchAction *BIA = dyn_cast<BindArchAction>(A)) {
  766. os << '"' << BIA->getArchName() << '"' << ", {"
  767. << PrintActions1(C, *BIA->begin(), Ids) << "}";
  768. } else if (CudaDeviceAction *CDA = dyn_cast<CudaDeviceAction>(A)) {
  769. os << '"' << CDA->getGpuArchName() << '"' << ", {"
  770. << PrintActions1(C, *CDA->begin(), Ids) << "}";
  771. } else {
  772. ActionList *AL;
  773. if (CudaHostAction *CHA = dyn_cast<CudaHostAction>(A)) {
  774. os << "{" << PrintActions1(C, *CHA->begin(), Ids) << "}"
  775. << ", gpu binaries ";
  776. AL = &CHA->getDeviceActions();
  777. } else
  778. AL = &A->getInputs();
  779. const char *Prefix = "{";
  780. for (Action *PreRequisite : *AL) {
  781. os << Prefix << PrintActions1(C, PreRequisite, Ids);
  782. Prefix = ", ";
  783. }
  784. os << "}";
  785. }
  786. unsigned Id = Ids.size();
  787. Ids[A] = Id;
  788. llvm::errs() << Id << ": " << os.str() << ", "
  789. << types::getTypeName(A->getType()) << "\n";
  790. return Id;
  791. }
  792. // Print the action graphs in a compilation C.
  793. // For example "clang -c file1.c file2.c" is composed of two subgraphs.
  794. void Driver::PrintActions(const Compilation &C) const {
  795. std::map<Action *, unsigned> Ids;
  796. for (Action *A : C.getActions())
  797. PrintActions1(C, A, Ids);
  798. }
  799. /// \brief Check whether the given input tree contains any compilation or
  800. /// assembly actions.
  801. static bool ContainsCompileOrAssembleAction(const Action *A) {
  802. if (isa<CompileJobAction>(A) || isa<BackendJobAction>(A) ||
  803. isa<AssembleJobAction>(A))
  804. return true;
  805. for (Action::const_iterator it = A->begin(), ie = A->end(); it != ie; ++it)
  806. if (ContainsCompileOrAssembleAction(*it))
  807. return true;
  808. return false;
  809. }
  810. void Driver::BuildUniversalActions(const ToolChain &TC, DerivedArgList &Args,
  811. const InputList &BAInputs,
  812. ActionList &Actions) const {
  813. llvm::PrettyStackTraceString CrashInfo("Building universal build actions");
  814. // Collect the list of architectures. Duplicates are allowed, but should only
  815. // be handled once (in the order seen).
  816. llvm::StringSet<> ArchNames;
  817. SmallVector<const char *, 4> Archs;
  818. for (Arg *A : Args) {
  819. if (A->getOption().matches(options::OPT_arch)) {
  820. // Validate the option here; we don't save the type here because its
  821. // particular spelling may participate in other driver choices.
  822. llvm::Triple::ArchType Arch =
  823. tools::darwin::getArchTypeForMachOArchName(A->getValue());
  824. if (Arch == llvm::Triple::UnknownArch) {
  825. Diag(clang::diag::err_drv_invalid_arch_name) << A->getAsString(Args);
  826. continue;
  827. }
  828. A->claim();
  829. if (ArchNames.insert(A->getValue()).second)
  830. Archs.push_back(A->getValue());
  831. }
  832. }
  833. // When there is no explicit arch for this platform, make sure we still bind
  834. // the architecture (to the default) so that -Xarch_ is handled correctly.
  835. if (!Archs.size())
  836. Archs.push_back(Args.MakeArgString(TC.getDefaultUniversalArchName()));
  837. ActionList SingleActions;
  838. BuildActions(TC, Args, BAInputs, SingleActions);
  839. // Add in arch bindings for every top level action, as well as lipo and
  840. // dsymutil steps if needed.
  841. for (unsigned i = 0, e = SingleActions.size(); i != e; ++i) {
  842. Action *Act = SingleActions[i];
  843. // Make sure we can lipo this kind of output. If not (and it is an actual
  844. // output) then we disallow, since we can't create an output file with the
  845. // right name without overwriting it. We could remove this oddity by just
  846. // changing the output names to include the arch, which would also fix
  847. // -save-temps. Compatibility wins for now.
  848. if (Archs.size() > 1 && !types::canLipoType(Act->getType()))
  849. Diag(clang::diag::err_drv_invalid_output_with_multiple_archs)
  850. << types::getTypeName(Act->getType());
  851. ActionList Inputs;
  852. for (unsigned i = 0, e = Archs.size(); i != e; ++i) {
  853. Inputs.push_back(
  854. new BindArchAction(std::unique_ptr<Action>(Act), Archs[i]));
  855. if (i != 0)
  856. Inputs.back()->setOwnsInputs(false);
  857. }
  858. // Lipo if necessary, we do it this way because we need to set the arch flag
  859. // so that -Xarch_ gets overwritten.
  860. if (Inputs.size() == 1 || Act->getType() == types::TY_Nothing)
  861. Actions.append(Inputs.begin(), Inputs.end());
  862. else
  863. Actions.push_back(new LipoJobAction(Inputs, Act->getType()));
  864. // Handle debug info queries.
  865. Arg *A = Args.getLastArg(options::OPT_g_Group);
  866. if (A && !A->getOption().matches(options::OPT_g0) &&
  867. !A->getOption().matches(options::OPT_gstabs) &&
  868. ContainsCompileOrAssembleAction(Actions.back())) {
  869. // Add a 'dsymutil' step if necessary, when debug info is enabled and we
  870. // have a compile input. We need to run 'dsymutil' ourselves in such cases
  871. // because the debug info will refer to a temporary object file which
  872. // will be removed at the end of the compilation process.
  873. if (Act->getType() == types::TY_Image) {
  874. ActionList Inputs;
  875. Inputs.push_back(Actions.back());
  876. Actions.pop_back();
  877. Actions.push_back(new DsymutilJobAction(Inputs, types::TY_dSYM));
  878. }
  879. // Verify the debug info output.
  880. if (Args.hasArg(options::OPT_verify_debug_info)) {
  881. std::unique_ptr<Action> VerifyInput(Actions.back());
  882. Actions.pop_back();
  883. Actions.push_back(new VerifyDebugInfoJobAction(std::move(VerifyInput),
  884. types::TY_Nothing));
  885. }
  886. }
  887. }
  888. }
  889. /// \brief Check that the file referenced by Value exists. If it doesn't,
  890. /// issue a diagnostic and return false.
  891. static bool DiagnoseInputExistence(const Driver &D, const DerivedArgList &Args,
  892. StringRef Value) {
  893. if (!D.getCheckInputsExist())
  894. return true;
  895. // stdin always exists.
  896. if (Value == "-")
  897. return true;
  898. SmallString<64> Path(Value);
  899. if (Arg *WorkDir = Args.getLastArg(options::OPT_working_directory)) {
  900. if (!llvm::sys::path::is_absolute(Path)) {
  901. SmallString<64> Directory(WorkDir->getValue());
  902. llvm::sys::path::append(Directory, Value);
  903. Path.assign(Directory);
  904. }
  905. }
  906. if (llvm::sys::fs::exists(Twine(Path)))
  907. return true;
  908. if (D.IsCLMode() && !llvm::sys::path::is_absolute(Twine(Path)) &&
  909. llvm::sys::Process::FindInEnvPath("LIB", Value))
  910. return true;
  911. D.Diag(clang::diag::err_drv_no_such_file) << Path;
  912. return false;
  913. }
  914. // Construct a the list of inputs and their types.
  915. void Driver::BuildInputs(const ToolChain &TC, DerivedArgList &Args,
  916. InputList &Inputs) const {
  917. // Track the current user specified (-x) input. We also explicitly track the
  918. // argument used to set the type; we only want to claim the type when we
  919. // actually use it, so we warn about unused -x arguments.
  920. types::ID InputType = types::TY_Nothing;
  921. Arg *InputTypeArg = nullptr;
  922. // The last /TC or /TP option sets the input type to C or C++ globally.
  923. if (Arg *TCTP = Args.getLastArgNoClaim(options::OPT__SLASH_TC,
  924. options::OPT__SLASH_TP)) {
  925. InputTypeArg = TCTP;
  926. InputType = TCTP->getOption().matches(options::OPT__SLASH_TC)
  927. ? types::TY_C
  928. : types::TY_CXX;
  929. arg_iterator it =
  930. Args.filtered_begin(options::OPT__SLASH_TC, options::OPT__SLASH_TP);
  931. const arg_iterator ie = Args.filtered_end();
  932. Arg *Previous = *it++;
  933. bool ShowNote = false;
  934. while (it != ie) {
  935. Diag(clang::diag::warn_drv_overriding_flag_option)
  936. << Previous->getSpelling() << (*it)->getSpelling();
  937. Previous = *it++;
  938. ShowNote = true;
  939. }
  940. if (ShowNote)
  941. Diag(clang::diag::note_drv_t_option_is_global);
  942. // No driver mode exposes -x and /TC or /TP; we don't support mixing them.
  943. assert(!Args.hasArg(options::OPT_x) && "-x and /TC or /TP is not allowed");
  944. }
  945. for (Arg *A : Args) {
  946. if (A->getOption().getKind() == Option::InputClass) {
  947. const char *Value = A->getValue();
  948. types::ID Ty = types::TY_INVALID;
  949. // Infer the input type if necessary.
  950. if (InputType == types::TY_Nothing) {
  951. // If there was an explicit arg for this, claim it.
  952. if (InputTypeArg)
  953. InputTypeArg->claim();
  954. // stdin must be handled specially.
  955. if (memcmp(Value, "-", 2) == 0) {
  956. // If running with -E, treat as a C input (this changes the builtin
  957. // macros, for example). This may be overridden by -ObjC below.
  958. //
  959. // Otherwise emit an error but still use a valid type to avoid
  960. // spurious errors (e.g., no inputs).
  961. if (!Args.hasArgNoClaim(options::OPT_E) && !CCCIsCPP())
  962. Diag(IsCLMode() ? clang::diag::err_drv_unknown_stdin_type_clang_cl
  963. : clang::diag::err_drv_unknown_stdin_type);
  964. Ty = types::TY_C;
  965. } else {
  966. // Otherwise lookup by extension.
  967. // Fallback is C if invoked as C preprocessor or Object otherwise.
  968. // We use a host hook here because Darwin at least has its own
  969. // idea of what .s is.
  970. if (const char *Ext = strrchr(Value, '.'))
  971. Ty = TC.LookupTypeForExtension(Ext + 1);
  972. if (Ty == types::TY_INVALID) {
  973. if (CCCIsCPP())
  974. Ty = types::TY_C;
  975. else
  976. Ty = types::TY_Object;
  977. }
  978. // If the driver is invoked as C++ compiler (like clang++ or c++) it
  979. // should autodetect some input files as C++ for g++ compatibility.
  980. if (CCCIsCXX()) {
  981. types::ID OldTy = Ty;
  982. Ty = types::lookupCXXTypeForCType(Ty);
  983. if (Ty != OldTy)
  984. Diag(clang::diag::warn_drv_treating_input_as_cxx)
  985. << getTypeName(OldTy) << getTypeName(Ty);
  986. }
  987. }
  988. // -ObjC and -ObjC++ override the default language, but only for "source
  989. // files". We just treat everything that isn't a linker input as a
  990. // source file.
  991. //
  992. // FIXME: Clean this up if we move the phase sequence into the type.
  993. if (Ty != types::TY_Object) {
  994. if (Args.hasArg(options::OPT_ObjC))
  995. Ty = types::TY_ObjC;
  996. else if (Args.hasArg(options::OPT_ObjCXX))
  997. Ty = types::TY_ObjCXX;
  998. }
  999. } else {
  1000. assert(InputTypeArg && "InputType set w/o InputTypeArg");
  1001. if (!InputTypeArg->getOption().matches(options::OPT_x)) {
  1002. // If emulating cl.exe, make sure that /TC and /TP don't affect input
  1003. // object files.
  1004. const char *Ext = strrchr(Value, '.');
  1005. if (Ext && TC.LookupTypeForExtension(Ext + 1) == types::TY_Object)
  1006. Ty = types::TY_Object;
  1007. }
  1008. if (Ty == types::TY_INVALID) {
  1009. Ty = InputType;
  1010. InputTypeArg->claim();
  1011. }
  1012. }
  1013. if (DiagnoseInputExistence(*this, Args, Value))
  1014. Inputs.push_back(std::make_pair(Ty, A));
  1015. } else if (A->getOption().matches(options::OPT__SLASH_Tc)) {
  1016. StringRef Value = A->getValue();
  1017. if (DiagnoseInputExistence(*this, Args, Value)) {
  1018. Arg *InputArg = MakeInputArg(Args, Opts, A->getValue());
  1019. Inputs.push_back(std::make_pair(types::TY_C, InputArg));
  1020. }
  1021. A->claim();
  1022. } else if (A->getOption().matches(options::OPT__SLASH_Tp)) {
  1023. StringRef Value = A->getValue();
  1024. if (DiagnoseInputExistence(*this, Args, Value)) {
  1025. Arg *InputArg = MakeInputArg(Args, Opts, A->getValue());
  1026. Inputs.push_back(std::make_pair(types::TY_CXX, InputArg));
  1027. }
  1028. A->claim();
  1029. } else if (A->getOption().hasFlag(options::LinkerInput)) {
  1030. // Just treat as object type, we could make a special type for this if
  1031. // necessary.
  1032. Inputs.push_back(std::make_pair(types::TY_Object, A));
  1033. } else if (A->getOption().matches(options::OPT_x)) {
  1034. InputTypeArg = A;
  1035. InputType = types::lookupTypeForTypeSpecifier(A->getValue());
  1036. A->claim();
  1037. // Follow gcc behavior and treat as linker input for invalid -x
  1038. // options. Its not clear why we shouldn't just revert to unknown; but
  1039. // this isn't very important, we might as well be bug compatible.
  1040. if (!InputType) {
  1041. Diag(clang::diag::err_drv_unknown_language) << A->getValue();
  1042. InputType = types::TY_Object;
  1043. }
  1044. }
  1045. }
  1046. if (CCCIsCPP() && Inputs.empty()) {
  1047. // If called as standalone preprocessor, stdin is processed
  1048. // if no other input is present.
  1049. Arg *A = MakeInputArg(Args, Opts, "-");
  1050. Inputs.push_back(std::make_pair(types::TY_C, A));
  1051. }
  1052. }
  1053. // For each unique --cuda-gpu-arch= argument creates a TY_CUDA_DEVICE input
  1054. // action and then wraps each in CudaDeviceAction paired with appropriate GPU
  1055. // arch name. If we're only building device-side code, each action remains
  1056. // independent. Otherwise we pass device-side actions as inputs to a new
  1057. // CudaHostAction which combines both host and device side actions.
  1058. static std::unique_ptr<Action>
  1059. buildCudaActions(const Driver &D, const ToolChain &TC, DerivedArgList &Args,
  1060. const Arg *InputArg, const types::ID InputType,
  1061. std::unique_ptr<Action> Current, ActionList &Actions) {
  1062. assert(InputType == types::TY_CUDA &&
  1063. "CUDA Actions only apply to CUDA inputs.");
  1064. // Collect all cuda_gpu_arch parameters, removing duplicates.
  1065. SmallVector<const char *, 4> GpuArchList;
  1066. llvm::StringSet<> GpuArchNames;
  1067. for (Arg *A : Args) {
  1068. if (A->getOption().matches(options::OPT_cuda_gpu_arch_EQ)) {
  1069. A->claim();
  1070. if (GpuArchNames.insert(A->getValue()).second)
  1071. GpuArchList.push_back(A->getValue());
  1072. }
  1073. }
  1074. // Default to sm_20 which is the lowest common denominator for supported GPUs.
  1075. // sm_20 code should work correctly, if suboptimally, on all newer GPUs.
  1076. if (GpuArchList.empty())
  1077. GpuArchList.push_back("sm_20");
  1078. // Replicate inputs for each GPU architecture.
  1079. Driver::InputList CudaDeviceInputs;
  1080. for (unsigned i = 0, e = GpuArchList.size(); i != e; ++i)
  1081. CudaDeviceInputs.push_back(std::make_pair(types::TY_CUDA_DEVICE, InputArg));
  1082. // Build actions for all device inputs.
  1083. ActionList CudaDeviceActions;
  1084. D.BuildActions(TC, Args, CudaDeviceInputs, CudaDeviceActions);
  1085. assert(GpuArchList.size() == CudaDeviceActions.size() &&
  1086. "Failed to create actions for all devices");
  1087. // Check whether any of device actions stopped before they could generate PTX.
  1088. bool PartialCompilation = false;
  1089. bool DeviceOnlyCompilation = Args.hasArg(options::OPT_cuda_device_only);
  1090. for (unsigned i = 0, e = GpuArchList.size(); i != e; ++i) {
  1091. if (CudaDeviceActions[i]->getKind() != Action::BackendJobClass) {
  1092. PartialCompilation = true;
  1093. break;
  1094. }
  1095. }
  1096. // Figure out what to do with device actions -- pass them as inputs to the
  1097. // host action or run each of them independently.
  1098. if (PartialCompilation || DeviceOnlyCompilation) {
  1099. // In case of partial or device-only compilation results of device actions
  1100. // are not consumed by the host action device actions have to be added to
  1101. // top-level actions list with AtTopLevel=true and run independently.
  1102. // -o is ambiguous if we have more than one top-level action.
  1103. if (Args.hasArg(options::OPT_o) &&
  1104. (!DeviceOnlyCompilation || GpuArchList.size() > 1)) {
  1105. D.Diag(clang::diag::err_drv_output_argument_with_multiple_files);
  1106. return nullptr;
  1107. }
  1108. for (unsigned i = 0, e = GpuArchList.size(); i != e; ++i)
  1109. Actions.push_back(
  1110. new CudaDeviceAction(std::unique_ptr<Action>(CudaDeviceActions[i]),
  1111. GpuArchList[i], /* AtTopLevel */ true));
  1112. // Kill host action in case of device-only compilation.
  1113. if (DeviceOnlyCompilation)
  1114. Current.reset(nullptr);
  1115. return Current;
  1116. } else {
  1117. // Outputs of device actions during complete CUDA compilation get created
  1118. // with AtTopLevel=false and become inputs for the host action.
  1119. ActionList DeviceActions;
  1120. for (unsigned i = 0, e = GpuArchList.size(); i != e; ++i)
  1121. DeviceActions.push_back(
  1122. new CudaDeviceAction(std::unique_ptr<Action>(CudaDeviceActions[i]),
  1123. GpuArchList[i], /* AtTopLevel */ false));
  1124. // Return a new host action that incorporates original host action and all
  1125. // device actions.
  1126. return std::unique_ptr<Action>(
  1127. new CudaHostAction(std::move(Current), DeviceActions));
  1128. }
  1129. }
  1130. void Driver::BuildActions(const ToolChain &TC, DerivedArgList &Args,
  1131. const InputList &Inputs, ActionList &Actions) const {
  1132. llvm::PrettyStackTraceString CrashInfo("Building compilation actions");
  1133. if (!SuppressMissingInputWarning && Inputs.empty()) {
  1134. Diag(clang::diag::err_drv_no_input_files);
  1135. return;
  1136. }
  1137. Arg *FinalPhaseArg;
  1138. phases::ID FinalPhase = getFinalPhase(Args, &FinalPhaseArg);
  1139. if (FinalPhase == phases::Link && Args.hasArg(options::OPT_emit_llvm)) {
  1140. Diag(clang::diag::err_drv_emit_llvm_link);
  1141. }
  1142. // Reject -Z* at the top level, these options should never have been exposed
  1143. // by gcc.
  1144. if (Arg *A = Args.getLastArg(options::OPT_Z_Joined))
  1145. Diag(clang::diag::err_drv_use_of_Z_option) << A->getAsString(Args);
  1146. // Diagnose misuse of /Fo.
  1147. if (Arg *A = Args.getLastArg(options::OPT__SLASH_Fo)) {
  1148. StringRef V = A->getValue();
  1149. if (Inputs.size() > 1 && !V.empty() &&
  1150. !llvm::sys::path::is_separator(V.back())) {
  1151. // Check whether /Fo tries to name an output file for multiple inputs.
  1152. Diag(clang::diag::err_drv_out_file_argument_with_multiple_sources)
  1153. << A->getSpelling() << V;
  1154. Args.eraseArg(options::OPT__SLASH_Fo);
  1155. }
  1156. }
  1157. // Diagnose misuse of /Fa.
  1158. if (Arg *A = Args.getLastArg(options::OPT__SLASH_Fa)) {
  1159. StringRef V = A->getValue();
  1160. if (Inputs.size() > 1 && !V.empty() &&
  1161. !llvm::sys::path::is_separator(V.back())) {
  1162. // Check whether /Fa tries to name an asm file for multiple inputs.
  1163. Diag(clang::diag::err_drv_out_file_argument_with_multiple_sources)
  1164. << A->getSpelling() << V;
  1165. Args.eraseArg(options::OPT__SLASH_Fa);
  1166. }
  1167. }
  1168. // Diagnose misuse of /o.
  1169. if (Arg *A = Args.getLastArg(options::OPT__SLASH_o)) {
  1170. if (A->getValue()[0] == '\0') {
  1171. // It has to have a value.
  1172. Diag(clang::diag::err_drv_missing_argument) << A->getSpelling() << 1;
  1173. Args.eraseArg(options::OPT__SLASH_o);
  1174. }
  1175. }
  1176. // Construct the actions to perform.
  1177. ActionList LinkerInputs;
  1178. llvm::SmallVector<phases::ID, phases::MaxNumberOfPhases> PL;
  1179. for (unsigned i = 0, e = Inputs.size(); i != e; ++i) {
  1180. types::ID InputType = Inputs[i].first;
  1181. const Arg *InputArg = Inputs[i].second;
  1182. PL.clear();
  1183. types::getCompilationPhases(InputType, PL);
  1184. // If the first step comes after the final phase we are doing as part of
  1185. // this compilation, warn the user about it.
  1186. phases::ID InitialPhase = PL[0];
  1187. if (InitialPhase > FinalPhase) {
  1188. // Claim here to avoid the more general unused warning.
  1189. InputArg->claim();
  1190. // Suppress all unused style warnings with -Qunused-arguments
  1191. if (Args.hasArg(options::OPT_Qunused_arguments))
  1192. continue;
  1193. // Special case when final phase determined by binary name, rather than
  1194. // by a command-line argument with a corresponding Arg.
  1195. if (CCCIsCPP())
  1196. Diag(clang::diag::warn_drv_input_file_unused_by_cpp)
  1197. << InputArg->getAsString(Args) << getPhaseName(InitialPhase);
  1198. // Special case '-E' warning on a previously preprocessed file to make
  1199. // more sense.
  1200. else if (InitialPhase == phases::Compile &&
  1201. FinalPhase == phases::Preprocess &&
  1202. getPreprocessedType(InputType) == types::TY_INVALID)
  1203. Diag(clang::diag::warn_drv_preprocessed_input_file_unused)
  1204. << InputArg->getAsString(Args) << !!FinalPhaseArg
  1205. << (FinalPhaseArg ? FinalPhaseArg->getOption().getName() : "");
  1206. else
  1207. Diag(clang::diag::warn_drv_input_file_unused)
  1208. << InputArg->getAsString(Args) << getPhaseName(InitialPhase)
  1209. << !!FinalPhaseArg
  1210. << (FinalPhaseArg ? FinalPhaseArg->getOption().getName() : "");
  1211. continue;
  1212. }
  1213. phases::ID CudaInjectionPhase;
  1214. if (isSaveTempsEnabled()) {
  1215. // All phases are done independently, inject GPU blobs during compilation
  1216. // phase as that's where we generate glue code to init them.
  1217. CudaInjectionPhase = phases::Compile;
  1218. } else {
  1219. // Assumes that clang does everything up until linking phase, so we inject
  1220. // cuda device actions at the last step before linking. Otherwise CUDA
  1221. // host action forces preprocessor into a separate invocation.
  1222. if (FinalPhase == phases::Link) {
  1223. for (auto i = PL.begin(), e = PL.end(); i != e; ++i) {
  1224. auto next = i + 1;
  1225. if (next != e && *next == phases::Link)
  1226. CudaInjectionPhase = *i;
  1227. }
  1228. } else
  1229. CudaInjectionPhase = FinalPhase;
  1230. }
  1231. // Build the pipeline for this file.
  1232. std::unique_ptr<Action> Current(new InputAction(*InputArg, InputType));
  1233. for (SmallVectorImpl<phases::ID>::iterator i = PL.begin(), e = PL.end();
  1234. i != e; ++i) {
  1235. phases::ID Phase = *i;
  1236. // We are done if this step is past what the user requested.
  1237. if (Phase > FinalPhase)
  1238. break;
  1239. // Queue linker inputs.
  1240. if (Phase == phases::Link) {
  1241. assert((i + 1) == e && "linking must be final compilation step.");
  1242. LinkerInputs.push_back(Current.release());
  1243. break;
  1244. }
  1245. // Some types skip the assembler phase (e.g., llvm-bc), but we can't
  1246. // encode this in the steps because the intermediate type depends on
  1247. // arguments. Just special case here.
  1248. if (Phase == phases::Assemble && Current->getType() != types::TY_PP_Asm)
  1249. continue;
  1250. // Otherwise construct the appropriate action.
  1251. Current = ConstructPhaseAction(TC, Args, Phase, std::move(Current));
  1252. if (InputType == types::TY_CUDA && Phase == CudaInjectionPhase &&
  1253. !Args.hasArg(options::OPT_cuda_host_only)) {
  1254. Current = buildCudaActions(*this, TC, Args, InputArg, InputType,
  1255. std::move(Current), Actions);
  1256. if (!Current)
  1257. break;
  1258. }
  1259. if (Current->getType() == types::TY_Nothing)
  1260. break;
  1261. }
  1262. // If we ended with something, add to the output list.
  1263. if (Current)
  1264. Actions.push_back(Current.release());
  1265. }
  1266. // Add a link action if necessary.
  1267. if (!LinkerInputs.empty())
  1268. Actions.push_back(new LinkJobAction(LinkerInputs, types::TY_Image));
  1269. // If we are linking, claim any options which are obviously only used for
  1270. // compilation.
  1271. if (FinalPhase == phases::Link && PL.size() == 1) {
  1272. Args.ClaimAllArgs(options::OPT_CompileOnly_Group);
  1273. Args.ClaimAllArgs(options::OPT_cl_compile_Group);
  1274. }
  1275. // Claim ignored clang-cl options.
  1276. Args.ClaimAllArgs(options::OPT_cl_ignored_Group);
  1277. }
  1278. std::unique_ptr<Action>
  1279. Driver::ConstructPhaseAction(const ToolChain &TC, const ArgList &Args,
  1280. phases::ID Phase,
  1281. std::unique_ptr<Action> Input) const {
  1282. llvm::PrettyStackTraceString CrashInfo("Constructing phase actions");
  1283. // Build the appropriate action.
  1284. switch (Phase) {
  1285. case phases::Link:
  1286. llvm_unreachable("link action invalid here.");
  1287. case phases::Preprocess: {
  1288. types::ID OutputTy;
  1289. // -{M, MM} alter the output type.
  1290. if (Args.hasArg(options::OPT_M, options::OPT_MM)) {
  1291. OutputTy = types::TY_Dependencies;
  1292. } else {
  1293. OutputTy = Input->getType();
  1294. if (!Args.hasFlag(options::OPT_frewrite_includes,
  1295. options::OPT_fno_rewrite_includes, false) &&
  1296. !CCGenDiagnostics)
  1297. OutputTy = types::getPreprocessedType(OutputTy);
  1298. assert(OutputTy != types::TY_INVALID &&
  1299. "Cannot preprocess this input type!");
  1300. }
  1301. return llvm::make_unique<PreprocessJobAction>(std::move(Input), OutputTy);
  1302. }
  1303. case phases::Precompile: {
  1304. types::ID OutputTy = types::TY_PCH;
  1305. if (Args.hasArg(options::OPT_fsyntax_only)) {
  1306. // Syntax checks should not emit a PCH file
  1307. OutputTy = types::TY_Nothing;
  1308. }
  1309. return llvm::make_unique<PrecompileJobAction>(std::move(Input), OutputTy);
  1310. }
  1311. case phases::Compile: {
  1312. if (Args.hasArg(options::OPT_fsyntax_only))
  1313. return llvm::make_unique<CompileJobAction>(std::move(Input),
  1314. types::TY_Nothing);
  1315. if (Args.hasArg(options::OPT_rewrite_objc))
  1316. return llvm::make_unique<CompileJobAction>(std::move(Input),
  1317. types::TY_RewrittenObjC);
  1318. if (Args.hasArg(options::OPT_rewrite_legacy_objc))
  1319. return llvm::make_unique<CompileJobAction>(std::move(Input),
  1320. types::TY_RewrittenLegacyObjC);
  1321. if (Args.hasArg(options::OPT__analyze, options::OPT__analyze_auto))
  1322. return llvm::make_unique<AnalyzeJobAction>(std::move(Input),
  1323. types::TY_Plist);
  1324. if (Args.hasArg(options::OPT__migrate))
  1325. return llvm::make_unique<MigrateJobAction>(std::move(Input),
  1326. types::TY_Remap);
  1327. if (Args.hasArg(options::OPT_emit_ast))
  1328. return llvm::make_unique<CompileJobAction>(std::move(Input),
  1329. types::TY_AST);
  1330. if (Args.hasArg(options::OPT_module_file_info))
  1331. return llvm::make_unique<CompileJobAction>(std::move(Input),
  1332. types::TY_ModuleFile);
  1333. if (Args.hasArg(options::OPT_verify_pch))
  1334. return llvm::make_unique<VerifyPCHJobAction>(std::move(Input),
  1335. types::TY_Nothing);
  1336. return llvm::make_unique<CompileJobAction>(std::move(Input),
  1337. types::TY_LLVM_BC);
  1338. }
  1339. case phases::Backend: {
  1340. if (IsUsingLTO(Args)) {
  1341. types::ID Output =
  1342. Args.hasArg(options::OPT_S) ? types::TY_LTO_IR : types::TY_LTO_BC;
  1343. return llvm::make_unique<BackendJobAction>(std::move(Input), Output);
  1344. }
  1345. if (Args.hasArg(options::OPT_emit_llvm)) {
  1346. types::ID Output =
  1347. Args.hasArg(options::OPT_S) ? types::TY_LLVM_IR : types::TY_LLVM_BC;
  1348. return llvm::make_unique<BackendJobAction>(std::move(Input), Output);
  1349. }
  1350. return llvm::make_unique<BackendJobAction>(std::move(Input),
  1351. types::TY_PP_Asm);
  1352. }
  1353. case phases::Assemble:
  1354. return llvm::make_unique<AssembleJobAction>(std::move(Input),
  1355. types::TY_Object);
  1356. }
  1357. llvm_unreachable("invalid phase in ConstructPhaseAction");
  1358. }
  1359. bool Driver::IsUsingLTO(const ArgList &Args) const {
  1360. return Args.hasFlag(options::OPT_flto, options::OPT_fno_lto, false);
  1361. }
  1362. void Driver::BuildJobs(Compilation &C) const {
  1363. llvm::PrettyStackTraceString CrashInfo("Building compilation jobs");
  1364. Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o);
  1365. // It is an error to provide a -o option if we are making multiple output
  1366. // files.
  1367. if (FinalOutput) {
  1368. unsigned NumOutputs = 0;
  1369. for (const Action *A : C.getActions())
  1370. if (A->getType() != types::TY_Nothing)
  1371. ++NumOutputs;
  1372. if (NumOutputs > 1) {
  1373. Diag(clang::diag::err_drv_output_argument_with_multiple_files);
  1374. FinalOutput = nullptr;
  1375. }
  1376. }
  1377. // Collect the list of architectures.
  1378. llvm::StringSet<> ArchNames;
  1379. if (C.getDefaultToolChain().getTriple().isOSBinFormatMachO())
  1380. for (const Arg *A : C.getArgs())
  1381. if (A->getOption().matches(options::OPT_arch))
  1382. ArchNames.insert(A->getValue());
  1383. for (Action *A : C.getActions()) {
  1384. // If we are linking an image for multiple archs then the linker wants
  1385. // -arch_multiple and -final_output <final image name>. Unfortunately, this
  1386. // doesn't fit in cleanly because we have to pass this information down.
  1387. //
  1388. // FIXME: This is a hack; find a cleaner way to integrate this into the
  1389. // process.
  1390. const char *LinkingOutput = nullptr;
  1391. if (isa<LipoJobAction>(A)) {
  1392. if (FinalOutput)
  1393. LinkingOutput = FinalOutput->getValue();
  1394. else
  1395. LinkingOutput = getDefaultImageName();
  1396. }
  1397. InputInfo II;
  1398. BuildJobsForAction(C, A, &C.getDefaultToolChain(),
  1399. /*BoundArch*/ nullptr,
  1400. /*AtTopLevel*/ true,
  1401. /*MultipleArchs*/ ArchNames.size() > 1,
  1402. /*LinkingOutput*/ LinkingOutput, II);
  1403. }
  1404. // If the user passed -Qunused-arguments or there were errors, don't warn
  1405. // about any unused arguments.
  1406. if (Diags.hasErrorOccurred() ||
  1407. C.getArgs().hasArg(options::OPT_Qunused_arguments))
  1408. return;
  1409. // Claim -### here.
  1410. (void)C.getArgs().hasArg(options::OPT__HASH_HASH_HASH);
  1411. // Claim --driver-mode, it was handled earlier.
  1412. (void)C.getArgs().hasArg(options::OPT_driver_mode);
  1413. (void)C.getArgs().hasArg(options::OPT_verify); // HLSL Change - claim -verify
  1414. for (Arg *A : C.getArgs()) {
  1415. // FIXME: It would be nice to be able to send the argument to the
  1416. // DiagnosticsEngine, so that extra values, position, and so on could be
  1417. // printed.
  1418. if (!A->isClaimed()) {
  1419. if (A->getOption().hasFlag(options::NoArgumentUnused))
  1420. continue;
  1421. // Suppress the warning automatically if this is just a flag, and it is an
  1422. // instance of an argument we already claimed.
  1423. const Option &Opt = A->getOption();
  1424. if (Opt.getKind() == Option::FlagClass) {
  1425. bool DuplicateClaimed = false;
  1426. for (const Arg *AA : C.getArgs().filtered(&Opt)) {
  1427. if (AA->isClaimed()) {
  1428. DuplicateClaimed = true;
  1429. break;
  1430. }
  1431. }
  1432. if (DuplicateClaimed)
  1433. continue;
  1434. }
  1435. Diag(clang::diag::warn_drv_unused_argument)
  1436. << A->getAsString(C.getArgs());
  1437. }
  1438. }
  1439. }
  1440. static const Tool *SelectToolForJob(Compilation &C, bool SaveTemps,
  1441. const ToolChain *TC, const JobAction *JA,
  1442. const ActionList *&Inputs) {
  1443. const Tool *ToolForJob = nullptr;
  1444. // See if we should look for a compiler with an integrated assembler. We match
  1445. // bottom up, so what we are actually looking for is an assembler job with a
  1446. // compiler input.
  1447. if (TC->useIntegratedAs() && !SaveTemps &&
  1448. !C.getArgs().hasArg(options::OPT_via_file_asm) &&
  1449. !C.getArgs().hasArg(options::OPT__SLASH_FA) &&
  1450. !C.getArgs().hasArg(options::OPT__SLASH_Fa) &&
  1451. isa<AssembleJobAction>(JA) && Inputs->size() == 1 &&
  1452. isa<BackendJobAction>(*Inputs->begin())) {
  1453. // A BackendJob is always preceded by a CompileJob, and without
  1454. // -save-temps they will always get combined together, so instead of
  1455. // checking the backend tool, check if the tool for the CompileJob
  1456. // has an integrated assembler.
  1457. const ActionList *BackendInputs = &(*Inputs)[0]->getInputs();
  1458. JobAction *CompileJA = cast<CompileJobAction>(*BackendInputs->begin());
  1459. const Tool *Compiler = TC->SelectTool(*CompileJA);
  1460. if (!Compiler)
  1461. return nullptr;
  1462. if (Compiler->hasIntegratedAssembler()) {
  1463. Inputs = &(*BackendInputs)[0]->getInputs();
  1464. ToolForJob = Compiler;
  1465. }
  1466. }
  1467. // A backend job should always be combined with the preceding compile job
  1468. // unless OPT_save_temps is enabled and the compiler is capable of emitting
  1469. // LLVM IR as an intermediate output.
  1470. if (isa<BackendJobAction>(JA)) {
  1471. // Check if the compiler supports emitting LLVM IR.
  1472. assert(Inputs->size() == 1);
  1473. JobAction *CompileJA;
  1474. // Extract real host action, if it's a CudaHostAction.
  1475. if (CudaHostAction *CudaHA = dyn_cast<CudaHostAction>(*Inputs->begin()))
  1476. CompileJA = cast<CompileJobAction>(*CudaHA->begin());
  1477. else
  1478. CompileJA = cast<CompileJobAction>(*Inputs->begin());
  1479. const Tool *Compiler = TC->SelectTool(*CompileJA);
  1480. if (!Compiler)
  1481. return nullptr;
  1482. if (!Compiler->canEmitIR() || !SaveTemps) {
  1483. Inputs = &(*Inputs)[0]->getInputs();
  1484. ToolForJob = Compiler;
  1485. }
  1486. }
  1487. // Otherwise use the tool for the current job.
  1488. if (!ToolForJob)
  1489. ToolForJob = TC->SelectTool(*JA);
  1490. // See if we should use an integrated preprocessor. We do so when we have
  1491. // exactly one input, since this is the only use case we care about
  1492. // (irrelevant since we don't support combine yet).
  1493. if (Inputs->size() == 1 && isa<PreprocessJobAction>(*Inputs->begin()) &&
  1494. !C.getArgs().hasArg(options::OPT_no_integrated_cpp) &&
  1495. !C.getArgs().hasArg(options::OPT_traditional_cpp) && !SaveTemps &&
  1496. !C.getArgs().hasArg(options::OPT_rewrite_objc) &&
  1497. ToolForJob->hasIntegratedCPP())
  1498. Inputs = &(*Inputs)[0]->getInputs();
  1499. return ToolForJob;
  1500. }
  1501. void Driver::BuildJobsForAction(Compilation &C, const Action *A,
  1502. const ToolChain *TC, const char *BoundArch,
  1503. bool AtTopLevel, bool MultipleArchs,
  1504. const char *LinkingOutput,
  1505. InputInfo &Result) const {
  1506. llvm::PrettyStackTraceString CrashInfo("Building compilation jobs");
  1507. InputInfoList CudaDeviceInputInfos;
  1508. if (const CudaHostAction *CHA = dyn_cast<CudaHostAction>(A)) {
  1509. InputInfo II;
  1510. // Append outputs of device jobs to the input list.
  1511. for (const Action *DA : CHA->getDeviceActions()) {
  1512. BuildJobsForAction(C, DA, TC, "", AtTopLevel,
  1513. /*MultipleArchs*/ false, LinkingOutput, II);
  1514. CudaDeviceInputInfos.push_back(II);
  1515. }
  1516. // Override current action with a real host compile action and continue
  1517. // processing it.
  1518. A = *CHA->begin();
  1519. }
  1520. if (const InputAction *IA = dyn_cast<InputAction>(A)) {
  1521. // FIXME: It would be nice to not claim this here; maybe the old scheme of
  1522. // just using Args was better?
  1523. const Arg &Input = IA->getInputArg();
  1524. Input.claim();
  1525. if (Input.getOption().matches(options::OPT_INPUT)) {
  1526. const char *Name = Input.getValue();
  1527. Result = InputInfo(Name, A->getType(), Name);
  1528. } else {
  1529. Result = InputInfo(&Input, A->getType(), "");
  1530. }
  1531. return;
  1532. }
  1533. if (const BindArchAction *BAA = dyn_cast<BindArchAction>(A)) {
  1534. const ToolChain *TC;
  1535. const char *ArchName = BAA->getArchName();
  1536. if (ArchName)
  1537. TC = &getToolChain(
  1538. C.getArgs(),
  1539. computeTargetTriple(DefaultTargetTriple, C.getArgs(), ArchName));
  1540. else
  1541. TC = &C.getDefaultToolChain();
  1542. BuildJobsForAction(C, *BAA->begin(), TC, ArchName, AtTopLevel,
  1543. MultipleArchs, LinkingOutput, Result);
  1544. return;
  1545. }
  1546. if (const CudaDeviceAction *CDA = dyn_cast<CudaDeviceAction>(A)) {
  1547. // Figure out which NVPTX triple to use for device-side compilation based on
  1548. // whether host is 64-bit.
  1549. llvm::Triple DeviceTriple(C.getDefaultToolChain().getTriple().isArch64Bit()
  1550. ? "nvptx64-nvidia-cuda"
  1551. : "nvptx-nvidia-cuda");
  1552. BuildJobsForAction(C, *CDA->begin(),
  1553. &getToolChain(C.getArgs(), DeviceTriple),
  1554. CDA->getGpuArchName(), CDA->isAtTopLevel(),
  1555. /*MultipleArchs*/ true, LinkingOutput, Result);
  1556. return;
  1557. }
  1558. const ActionList *Inputs = &A->getInputs();
  1559. const JobAction *JA = cast<JobAction>(A);
  1560. const Tool *T = SelectToolForJob(C, isSaveTempsEnabled(), TC, JA, Inputs);
  1561. if (!T)
  1562. return;
  1563. // Only use pipes when there is exactly one input.
  1564. InputInfoList InputInfos;
  1565. for (const Action *Input : *Inputs) {
  1566. // Treat dsymutil and verify sub-jobs as being at the top-level too, they
  1567. // shouldn't get temporary output names.
  1568. // FIXME: Clean this up.
  1569. bool SubJobAtTopLevel = false;
  1570. if (AtTopLevel && (isa<DsymutilJobAction>(A) || isa<VerifyJobAction>(A)))
  1571. SubJobAtTopLevel = true;
  1572. InputInfo II;
  1573. BuildJobsForAction(C, Input, TC, BoundArch, SubJobAtTopLevel, MultipleArchs,
  1574. LinkingOutput, II);
  1575. InputInfos.push_back(II);
  1576. }
  1577. // Always use the first input as the base input.
  1578. const char *BaseInput = InputInfos[0].getBaseInput();
  1579. // ... except dsymutil actions, which use their actual input as the base
  1580. // input.
  1581. if (JA->getType() == types::TY_dSYM)
  1582. BaseInput = InputInfos[0].getFilename();
  1583. // Append outputs of cuda device jobs to the input list
  1584. if (CudaDeviceInputInfos.size())
  1585. InputInfos.append(CudaDeviceInputInfos.begin(), CudaDeviceInputInfos.end());
  1586. // Determine the place to write output to, if any.
  1587. if (JA->getType() == types::TY_Nothing)
  1588. Result = InputInfo(A->getType(), BaseInput);
  1589. else
  1590. Result = InputInfo(GetNamedOutputPath(C, *JA, BaseInput, BoundArch,
  1591. AtTopLevel, MultipleArchs),
  1592. A->getType(), BaseInput);
  1593. if (CCCPrintBindings && !CCGenDiagnostics) {
  1594. llvm::errs() << "# \"" << T->getToolChain().getTripleString() << '"'
  1595. << " - \"" << T->getName() << "\", inputs: [";
  1596. for (unsigned i = 0, e = InputInfos.size(); i != e; ++i) {
  1597. llvm::errs() << InputInfos[i].getAsString();
  1598. if (i + 1 != e)
  1599. llvm::errs() << ", ";
  1600. }
  1601. llvm::errs() << "], output: " << Result.getAsString() << "\n";
  1602. } else {
  1603. T->ConstructJob(C, *JA, Result, InputInfos,
  1604. C.getArgsForToolChain(TC, BoundArch), LinkingOutput);
  1605. }
  1606. }
  1607. const char *Driver::getDefaultImageName() const {
  1608. llvm::Triple Target(llvm::Triple::normalize(DefaultTargetTriple));
  1609. return Target.isOSWindows() ? "a.exe" : "a.out";
  1610. }
  1611. /// \brief Create output filename based on ArgValue, which could either be a
  1612. /// full filename, filename without extension, or a directory. If ArgValue
  1613. /// does not provide a filename, then use BaseName, and use the extension
  1614. /// suitable for FileType.
  1615. static const char *MakeCLOutputFilename(const ArgList &Args, StringRef ArgValue,
  1616. StringRef BaseName,
  1617. types::ID FileType) {
  1618. SmallString<128> Filename = ArgValue;
  1619. if (ArgValue.empty()) {
  1620. // If the argument is empty, output to BaseName in the current dir.
  1621. Filename = BaseName;
  1622. } else if (llvm::sys::path::is_separator(Filename.back())) {
  1623. // If the argument is a directory, output to BaseName in that dir.
  1624. llvm::sys::path::append(Filename, BaseName);
  1625. }
  1626. if (!llvm::sys::path::has_extension(ArgValue)) {
  1627. // If the argument didn't provide an extension, then set it.
  1628. const char *Extension = types::getTypeTempSuffix(FileType, true);
  1629. if (FileType == types::TY_Image &&
  1630. Args.hasArg(options::OPT__SLASH_LD, options::OPT__SLASH_LDd)) {
  1631. // The output file is a dll.
  1632. Extension = "dll";
  1633. }
  1634. llvm::sys::path::replace_extension(Filename, Extension);
  1635. }
  1636. return Args.MakeArgString(Filename.c_str());
  1637. }
  1638. const char *Driver::GetNamedOutputPath(Compilation &C, const JobAction &JA,
  1639. const char *BaseInput,
  1640. const char *BoundArch, bool AtTopLevel,
  1641. bool MultipleArchs) const {
  1642. llvm::PrettyStackTraceString CrashInfo("Computing output path");
  1643. // Output to a user requested destination?
  1644. if (AtTopLevel && !isa<DsymutilJobAction>(JA) && !isa<VerifyJobAction>(JA)) {
  1645. if (Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o))
  1646. return C.addResultFile(FinalOutput->getValue(), &JA);
  1647. }
  1648. // For /P, preprocess to file named after BaseInput.
  1649. if (C.getArgs().hasArg(options::OPT__SLASH_P)) {
  1650. assert(AtTopLevel && isa<PreprocessJobAction>(JA));
  1651. StringRef BaseName = llvm::sys::path::filename(BaseInput);
  1652. StringRef NameArg;
  1653. if (Arg *A = C.getArgs().getLastArg(options::OPT__SLASH_Fi))
  1654. NameArg = A->getValue();
  1655. return C.addResultFile(
  1656. MakeCLOutputFilename(C.getArgs(), NameArg, BaseName, types::TY_PP_C),
  1657. &JA);
  1658. }
  1659. // Default to writing to stdout?
  1660. if (AtTopLevel && !CCGenDiagnostics &&
  1661. (isa<PreprocessJobAction>(JA) || JA.getType() == types::TY_ModuleFile))
  1662. return "-";
  1663. // Is this the assembly listing for /FA?
  1664. if (JA.getType() == types::TY_PP_Asm &&
  1665. (C.getArgs().hasArg(options::OPT__SLASH_FA) ||
  1666. C.getArgs().hasArg(options::OPT__SLASH_Fa))) {
  1667. // Use /Fa and the input filename to determine the asm file name.
  1668. StringRef BaseName = llvm::sys::path::filename(BaseInput);
  1669. StringRef FaValue = C.getArgs().getLastArgValue(options::OPT__SLASH_Fa);
  1670. return C.addResultFile(
  1671. MakeCLOutputFilename(C.getArgs(), FaValue, BaseName, JA.getType()),
  1672. &JA);
  1673. }
  1674. // Output to a temporary file?
  1675. if ((!AtTopLevel && !isSaveTempsEnabled() &&
  1676. !C.getArgs().hasArg(options::OPT__SLASH_Fo)) ||
  1677. CCGenDiagnostics) {
  1678. StringRef Name = llvm::sys::path::filename(BaseInput);
  1679. std::pair<StringRef, StringRef> Split = Name.split('.');
  1680. std::string TmpName = GetTemporaryPath(
  1681. Split.first, types::getTypeTempSuffix(JA.getType(), IsCLMode()));
  1682. return C.addTempFile(C.getArgs().MakeArgString(TmpName.c_str()));
  1683. }
  1684. SmallString<128> BasePath(BaseInput);
  1685. StringRef BaseName;
  1686. // Dsymutil actions should use the full path.
  1687. if (isa<DsymutilJobAction>(JA) || isa<VerifyJobAction>(JA))
  1688. BaseName = BasePath;
  1689. else
  1690. BaseName = llvm::sys::path::filename(BasePath);
  1691. // Determine what the derived output name should be.
  1692. const char *NamedOutput;
  1693. if (JA.getType() == types::TY_Object &&
  1694. C.getArgs().hasArg(options::OPT__SLASH_Fo, options::OPT__SLASH_o)) {
  1695. // The /Fo or /o flag decides the object filename.
  1696. StringRef Val =
  1697. C.getArgs()
  1698. .getLastArg(options::OPT__SLASH_Fo, options::OPT__SLASH_o)
  1699. ->getValue();
  1700. NamedOutput =
  1701. MakeCLOutputFilename(C.getArgs(), Val, BaseName, types::TY_Object);
  1702. } else if (JA.getType() == types::TY_Image &&
  1703. C.getArgs().hasArg(options::OPT__SLASH_Fe,
  1704. options::OPT__SLASH_o)) {
  1705. // The /Fe or /o flag names the linked file.
  1706. StringRef Val =
  1707. C.getArgs()
  1708. .getLastArg(options::OPT__SLASH_Fe, options::OPT__SLASH_o)
  1709. ->getValue();
  1710. NamedOutput =
  1711. MakeCLOutputFilename(C.getArgs(), Val, BaseName, types::TY_Image);
  1712. } else if (JA.getType() == types::TY_Image) {
  1713. if (IsCLMode()) {
  1714. // clang-cl uses BaseName for the executable name.
  1715. NamedOutput =
  1716. MakeCLOutputFilename(C.getArgs(), "", BaseName, types::TY_Image);
  1717. } else if (MultipleArchs && BoundArch) {
  1718. SmallString<128> Output(getDefaultImageName());
  1719. Output += "-";
  1720. Output.append(BoundArch);
  1721. NamedOutput = C.getArgs().MakeArgString(Output.c_str());
  1722. } else
  1723. NamedOutput = getDefaultImageName();
  1724. } else {
  1725. const char *Suffix = types::getTypeTempSuffix(JA.getType(), IsCLMode());
  1726. assert(Suffix && "All types used for output should have a suffix.");
  1727. std::string::size_type End = std::string::npos;
  1728. if (!types::appendSuffixForType(JA.getType()))
  1729. End = BaseName.rfind('.');
  1730. SmallString<128> Suffixed(BaseName.substr(0, End));
  1731. if (MultipleArchs && BoundArch) {
  1732. Suffixed += "-";
  1733. Suffixed.append(BoundArch);
  1734. }
  1735. // When using both -save-temps and -emit-llvm, use a ".tmp.bc" suffix for
  1736. // the unoptimized bitcode so that it does not get overwritten by the ".bc"
  1737. // optimized bitcode output.
  1738. if (!AtTopLevel && C.getArgs().hasArg(options::OPT_emit_llvm) &&
  1739. JA.getType() == types::TY_LLVM_BC)
  1740. Suffixed += ".tmp";
  1741. Suffixed += '.';
  1742. Suffixed += Suffix;
  1743. NamedOutput = C.getArgs().MakeArgString(Suffixed.c_str());
  1744. }
  1745. // Prepend object file path if -save-temps=obj
  1746. if (!AtTopLevel && isSaveTempsObj() && C.getArgs().hasArg(options::OPT_o) &&
  1747. JA.getType() != types::TY_PCH) {
  1748. Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o);
  1749. SmallString<128> TempPath(FinalOutput->getValue());
  1750. llvm::sys::path::remove_filename(TempPath);
  1751. StringRef OutputFileName = llvm::sys::path::filename(NamedOutput);
  1752. llvm::sys::path::append(TempPath, OutputFileName);
  1753. NamedOutput = C.getArgs().MakeArgString(TempPath.c_str());
  1754. }
  1755. // If we're saving temps and the temp file conflicts with the input file,
  1756. // then avoid overwriting input file.
  1757. if (!AtTopLevel && isSaveTempsEnabled() && NamedOutput == BaseName) {
  1758. bool SameFile = false;
  1759. SmallString<256> Result;
  1760. llvm::sys::fs::current_path(Result);
  1761. llvm::sys::path::append(Result, BaseName);
  1762. llvm::sys::fs::equivalent(BaseInput, Result.c_str(), SameFile);
  1763. // Must share the same path to conflict.
  1764. if (SameFile) {
  1765. StringRef Name = llvm::sys::path::filename(BaseInput);
  1766. std::pair<StringRef, StringRef> Split = Name.split('.');
  1767. std::string TmpName = GetTemporaryPath(
  1768. Split.first, types::getTypeTempSuffix(JA.getType(), IsCLMode()));
  1769. return C.addTempFile(C.getArgs().MakeArgString(TmpName.c_str()));
  1770. }
  1771. }
  1772. // As an annoying special case, PCH generation doesn't strip the pathname.
  1773. if (JA.getType() == types::TY_PCH) {
  1774. llvm::sys::path::remove_filename(BasePath);
  1775. if (BasePath.empty())
  1776. BasePath = NamedOutput;
  1777. else
  1778. llvm::sys::path::append(BasePath, NamedOutput);
  1779. return C.addResultFile(C.getArgs().MakeArgString(BasePath.c_str()), &JA);
  1780. } else {
  1781. return C.addResultFile(NamedOutput, &JA);
  1782. }
  1783. }
  1784. std::string Driver::GetFilePath(const char *Name, const ToolChain &TC) const {
  1785. // Respect a limited subset of the '-Bprefix' functionality in GCC by
  1786. // attempting to use this prefix when looking for file paths.
  1787. for (const std::string &Dir : PrefixDirs) {
  1788. if (Dir.empty())
  1789. continue;
  1790. SmallString<128> P(Dir[0] == '=' ? SysRoot + Dir.substr(1) : Dir);
  1791. llvm::sys::path::append(P, Name);
  1792. if (llvm::sys::fs::exists(Twine(P)))
  1793. return P.str();
  1794. }
  1795. SmallString<128> P(ResourceDir);
  1796. llvm::sys::path::append(P, Name);
  1797. if (llvm::sys::fs::exists(Twine(P)))
  1798. return P.str();
  1799. for (const std::string &Dir : TC.getFilePaths()) {
  1800. if (Dir.empty())
  1801. continue;
  1802. SmallString<128> P(Dir[0] == '=' ? SysRoot + Dir.substr(1) : Dir);
  1803. llvm::sys::path::append(P, Name);
  1804. if (llvm::sys::fs::exists(Twine(P)))
  1805. return P.str();
  1806. }
  1807. return Name;
  1808. }
  1809. void Driver::generatePrefixedToolNames(
  1810. const char *Tool, const ToolChain &TC,
  1811. SmallVectorImpl<std::string> &Names) const {
  1812. // FIXME: Needs a better variable than DefaultTargetTriple
  1813. Names.emplace_back(DefaultTargetTriple + "-" + Tool);
  1814. Names.emplace_back(Tool);
  1815. }
  1816. static bool ScanDirForExecutable(SmallString<128> &Dir,
  1817. ArrayRef<std::string> Names) {
  1818. for (const auto &Name : Names) {
  1819. llvm::sys::path::append(Dir, Name);
  1820. if (llvm::sys::fs::can_execute(Twine(Dir)))
  1821. return true;
  1822. llvm::sys::path::remove_filename(Dir);
  1823. }
  1824. return false;
  1825. }
  1826. std::string Driver::GetProgramPath(const char *Name,
  1827. const ToolChain &TC) const {
  1828. SmallVector<std::string, 2> TargetSpecificExecutables;
  1829. generatePrefixedToolNames(Name, TC, TargetSpecificExecutables);
  1830. // Respect a limited subset of the '-Bprefix' functionality in GCC by
  1831. // attempting to use this prefix when looking for program paths.
  1832. for (const auto &PrefixDir : PrefixDirs) {
  1833. if (llvm::sys::fs::is_directory(PrefixDir)) {
  1834. SmallString<128> P(PrefixDir);
  1835. if (ScanDirForExecutable(P, TargetSpecificExecutables))
  1836. return P.str();
  1837. } else {
  1838. SmallString<128> P(PrefixDir + Name);
  1839. if (llvm::sys::fs::can_execute(Twine(P)))
  1840. return P.str();
  1841. }
  1842. }
  1843. const ToolChain::path_list &List = TC.getProgramPaths();
  1844. for (const auto &Path : List) {
  1845. SmallString<128> P(Path);
  1846. if (ScanDirForExecutable(P, TargetSpecificExecutables))
  1847. return P.str();
  1848. }
  1849. // If all else failed, search the path.
  1850. for (const auto &TargetSpecificExecutable : TargetSpecificExecutables)
  1851. if (llvm::ErrorOr<std::string> P =
  1852. llvm::sys::findProgramByName(TargetSpecificExecutable))
  1853. return *P;
  1854. return Name;
  1855. }
  1856. std::string Driver::GetTemporaryPath(StringRef Prefix,
  1857. const char *Suffix) const {
  1858. SmallString<128> Path;
  1859. std::error_code EC = llvm::sys::fs::createTemporaryFile(Prefix, Suffix, Path);
  1860. if (EC) {
  1861. Diag(clang::diag::err_unable_to_make_temp) << EC.message();
  1862. return "";
  1863. }
  1864. return Path.str();
  1865. }
  1866. const ToolChain &Driver::getToolChain(const ArgList &Args,
  1867. const llvm::Triple &Target) const {
  1868. ToolChain *&TC = ToolChains[Target.str()];
  1869. #if 0 // HLSL Change - remove toolchains
  1870. if (!TC) {
  1871. switch (Target.getOS()) {
  1872. case llvm::Triple::CloudABI:
  1873. TC = new toolchains::CloudABI(*this, Target, Args);
  1874. break;
  1875. case llvm::Triple::Darwin:
  1876. case llvm::Triple::MacOSX:
  1877. case llvm::Triple::IOS:
  1878. TC = new toolchains::DarwinClang(*this, Target, Args);
  1879. break;
  1880. case llvm::Triple::DragonFly:
  1881. TC = new toolchains::DragonFly(*this, Target, Args);
  1882. break;
  1883. case llvm::Triple::OpenBSD:
  1884. TC = new toolchains::OpenBSD(*this, Target, Args);
  1885. break;
  1886. case llvm::Triple::Bitrig:
  1887. TC = new toolchains::Bitrig(*this, Target, Args);
  1888. break;
  1889. case llvm::Triple::NetBSD:
  1890. TC = new toolchains::NetBSD(*this, Target, Args);
  1891. break;
  1892. case llvm::Triple::FreeBSD:
  1893. TC = new toolchains::FreeBSD(*this, Target, Args);
  1894. break;
  1895. case llvm::Triple::Minix:
  1896. TC = new toolchains::Minix(*this, Target, Args);
  1897. break;
  1898. case llvm::Triple::Linux:
  1899. if (Target.getArch() == llvm::Triple::hexagon)
  1900. TC = new toolchains::Hexagon_TC(*this, Target, Args);
  1901. else
  1902. TC = new toolchains::Linux(*this, Target, Args);
  1903. break;
  1904. case llvm::Triple::NaCl:
  1905. TC = new toolchains::NaCl_TC(*this, Target, Args);
  1906. break;
  1907. case llvm::Triple::Solaris:
  1908. TC = new toolchains::Solaris(*this, Target, Args);
  1909. break;
  1910. case llvm::Triple::Win32:
  1911. switch (Target.getEnvironment()) {
  1912. default:
  1913. if (Target.isOSBinFormatELF())
  1914. TC = new toolchains::Generic_ELF(*this, Target, Args);
  1915. else if (Target.isOSBinFormatMachO())
  1916. TC = new toolchains::MachO(*this, Target, Args);
  1917. else
  1918. TC = new toolchains::Generic_GCC(*this, Target, Args);
  1919. break;
  1920. case llvm::Triple::GNU:
  1921. TC = new toolchains::MinGW(*this, Target, Args);
  1922. break;
  1923. case llvm::Triple::Itanium:
  1924. TC = new toolchains::CrossWindowsToolChain(*this, Target, Args);
  1925. break;
  1926. case llvm::Triple::MSVC:
  1927. case llvm::Triple::UnknownEnvironment:
  1928. TC = new toolchains::MSVCToolChain(*this, Target, Args);
  1929. break;
  1930. }
  1931. break;
  1932. case llvm::Triple::CUDA:
  1933. TC = new toolchains::CudaToolChain(*this, Target, Args);
  1934. break;
  1935. default:
  1936. // Of these targets, Hexagon is the only one that might have
  1937. // an OS of Linux, in which case it got handled above already.
  1938. if (Target.getArchName() == "tce")
  1939. TC = new toolchains::TCEToolChain(*this, Target, Args);
  1940. else if (Target.getArch() == llvm::Triple::hexagon)
  1941. TC = new toolchains::Hexagon_TC(*this, Target, Args);
  1942. else if (Target.getArch() == llvm::Triple::xcore)
  1943. TC = new toolchains::XCore(*this, Target, Args);
  1944. else if (Target.getArch() == llvm::Triple::shave)
  1945. TC = new toolchains::SHAVEToolChain(*this, Target, Args);
  1946. else if (Target.isOSBinFormatELF())
  1947. TC = new toolchains::Generic_ELF(*this, Target, Args);
  1948. else if (Target.isOSBinFormatMachO())
  1949. TC = new toolchains::MachO(*this, Target, Args);
  1950. else
  1951. TC = new toolchains::Generic_GCC(*this, Target, Args);
  1952. break;
  1953. }
  1954. }
  1955. #else // HLSL Change - remove toolchains
  1956. // TODO: revisit for HLSL proper
  1957. TC = new toolchains::Generic_GCC(*this, Target, Args);
  1958. #endif
  1959. return *TC;
  1960. }
  1961. bool Driver::ShouldUseClangCompiler(const JobAction &JA) const {
  1962. // Say "no" if there is not exactly one input of a type clang understands.
  1963. if (JA.size() != 1 || !types::isAcceptedByClang((*JA.begin())->getType()))
  1964. return false;
  1965. // And say "no" if this is not a kind of action clang understands.
  1966. if (!isa<PreprocessJobAction>(JA) && !isa<PrecompileJobAction>(JA) &&
  1967. !isa<CompileJobAction>(JA) && !isa<BackendJobAction>(JA))
  1968. return false;
  1969. return true;
  1970. }
  1971. /// GetReleaseVersion - Parse (([0-9]+)(.([0-9]+)(.([0-9]+)?))?)? and return the
  1972. /// grouped values as integers. Numbers which are not provided are set to 0.
  1973. ///
  1974. /// \return True if the entire string was parsed (9.2), or all groups were
  1975. /// parsed (10.3.5extrastuff).
  1976. bool Driver::GetReleaseVersion(const char *Str, unsigned &Major,
  1977. unsigned &Minor, unsigned &Micro,
  1978. bool &HadExtra) {
  1979. HadExtra = false;
  1980. Major = Minor = Micro = 0;
  1981. if (*Str == '\0')
  1982. return false;
  1983. char *End;
  1984. Major = (unsigned)strtol(Str, &End, 10);
  1985. if (*Str != '\0' && *End == '\0')
  1986. return true;
  1987. if (*End != '.')
  1988. return false;
  1989. Str = End + 1;
  1990. Minor = (unsigned)strtol(Str, &End, 10);
  1991. if (*Str != '\0' && *End == '\0')
  1992. return true;
  1993. if (*End != '.')
  1994. return false;
  1995. Str = End + 1;
  1996. Micro = (unsigned)strtol(Str, &End, 10);
  1997. if (*Str != '\0' && *End == '\0')
  1998. return true;
  1999. if (Str == End)
  2000. return false;
  2001. HadExtra = true;
  2002. return true;
  2003. }
  2004. std::pair<unsigned, unsigned> Driver::getIncludeExcludeOptionFlagMasks() const {
  2005. unsigned IncludedFlagsBitmask = 0;
  2006. unsigned ExcludedFlagsBitmask = options::NoDriverOption;
  2007. if (Mode == CLMode) {
  2008. // Include CL and Core options.
  2009. IncludedFlagsBitmask |= options::CLOption;
  2010. IncludedFlagsBitmask |= options::CoreOption;
  2011. } else {
  2012. ExcludedFlagsBitmask |= options::CLOption;
  2013. }
  2014. return std::make_pair(IncludedFlagsBitmask, ExcludedFlagsBitmask);
  2015. }
  2016. bool clang::driver::isOptimizationLevelFast(const ArgList &Args) {
  2017. return Args.hasFlag(options::OPT_Ofast, options::OPT_O_Group, false);
  2018. }