blob: 61b277df1529a07d43f575ea6e0c05072ac08e7f [file] [log] [blame]
Nick Lewyckye47c2452010-09-23 23:48:20 +00001//===--- Driver.cpp - Clang GCC Compatible Driver -------------------------===//
Daniel Dunbar544ecd12009-03-02 19:59:07 +00002//
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
Daniel Dunbar544ecd12009-03-02 19:59:07 +000010#include "clang/Driver/Driver.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000011#include "InputInfo.h"
12#include "ToolChains.h"
13#include "clang/Basic/Version.h"
Benjamin Kramerd45b2052015-10-07 15:48:01 +000014#include "clang/Basic/VirtualFileSystem.h"
Alp Toker1d257e12014-06-04 03:28:55 +000015#include "clang/Config/config.h"
Daniel Dunbar1688f1a2009-03-12 07:58:46 +000016#include "clang/Driver/Action.h"
Daniel Dunbarb2cd66b2009-03-04 20:49:20 +000017#include "clang/Driver/Compilation.h"
Daniel Dunbarc0b3e952009-03-12 08:55:43 +000018#include "clang/Driver/DriverDiagnostic.h"
Daniel Dunbare75d8342009-03-16 06:56:51 +000019#include "clang/Driver/Job.h"
Daniel Dunbarb2cd66b2009-03-04 20:49:20 +000020#include "clang/Driver/Options.h"
Peter Collingbournea4ccff32015-02-20 20:30:56 +000021#include "clang/Driver/SanitizerArgs.h"
Daniel Dunbare75d8342009-03-16 06:56:51 +000022#include "clang/Driver/Tool.h"
23#include "clang/Driver/ToolChain.h"
Chris Lattnerce6c42f2011-03-23 04:04:01 +000024#include "llvm/ADT/ArrayRef.h"
Hans Wennborg6ddc6902013-07-27 00:23:45 +000025#include "llvm/ADT/STLExtras.h"
Justin Lebar62907612016-07-06 21:21:39 +000026#include "llvm/ADT/SmallSet.h"
Hans Wennborg23d26a32014-06-18 17:21:50 +000027#include "llvm/ADT/StringExtras.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000028#include "llvm/ADT/StringSet.h"
Hans Wennborg70850d82013-07-18 20:29:38 +000029#include "llvm/ADT/StringSwitch.h"
Reid Kleckner898229a2013-06-14 17:17:23 +000030#include "llvm/Option/Arg.h"
31#include "llvm/Option/ArgList.h"
Chandler Carruth5553d0d2014-01-07 11:51:46 +000032#include "llvm/Option/OptSpecifier.h"
Reid Kleckner898229a2013-06-14 17:17:23 +000033#include "llvm/Option/OptTable.h"
34#include "llvm/Option/Option.h"
David Blaikie79000202011-09-23 05:57:42 +000035#include "llvm/Support/ErrorHandling.h"
Michael J. Spencerf28df4c2010-12-17 21:22:22 +000036#include "llvm/Support/FileSystem.h"
Michael J. Spencer8aaf4992010-11-29 18:12:39 +000037#include "llvm/Support/Path.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000038#include "llvm/Support/PrettyStackTrace.h"
Hans Wennborg23d26a32014-06-18 17:21:50 +000039#include "llvm/Support/Process.h"
Michael J. Spencer8aaf4992010-11-29 18:12:39 +000040#include "llvm/Support/Program.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000041#include "llvm/Support/raw_ostream.h"
Dylan Noblesmith4f4e7452012-02-02 00:40:14 +000042#include <map>
Ahmed Charlesdfca6f92014-03-09 11:36:40 +000043#include <memory>
Benjamin Kramercfeacf52016-05-27 14:27:13 +000044#include <utility>
Dylan Noblesmith86780e92012-02-01 14:25:28 +000045
Daniel Dunbarb2cd66b2009-03-04 20:49:20 +000046using namespace clang::driver;
Chris Lattnerada1c912009-03-26 05:56:24 +000047using namespace clang;
Reid Kleckner898229a2013-06-14 17:17:23 +000048using namespace llvm::opt;
Daniel Dunbarb2cd66b2009-03-04 20:49:20 +000049
Reid Kleckner68eb60b2015-02-02 22:41:48 +000050Driver::Driver(StringRef ClangExecutable, StringRef DefaultTargetTriple,
Benjamin Kramerd45b2052015-10-07 15:48:01 +000051 DiagnosticsEngine &Diags,
52 IntrusiveRefCntPtr<vfs::FileSystem> VFS)
Benjamin Kramercfeacf52016-05-27 14:27:13 +000053 : Opts(createDriverOptTable()), Diags(Diags), VFS(std::move(VFS)),
54 Mode(GCCMode), SaveTemps(SaveTempsNone), BitcodeEmbed(EmbedNone),
55 LTOMode(LTOK_None), ClangExecutable(ClangExecutable),
Reid Kleckner68eb60b2015-02-02 22:41:48 +000056 SysRoot(DEFAULT_SYSROOT), UseStdLib(true),
Reid Kleckner68eb60b2015-02-02 22:41:48 +000057 DriverTitle("clang LLVM compiler"), CCPrintOptionsFilename(nullptr),
58 CCPrintHeadersFilename(nullptr), CCLogDiagnosticsFilename(nullptr),
59 CCCPrintBindings(false), CCPrintHeaders(false), CCLogDiagnostics(false),
Vedant Kumarf2030b92016-07-18 19:56:33 +000060 CCGenDiagnostics(false), DefaultTargetTriple(DefaultTargetTriple),
61 CCCGenericGCCName(""), CheckInputsExist(true), CCCUsePCH(true),
62 SuppressMissingInputWarning(false) {
Daniel Dunbar3f3e2cd2010-01-20 02:35:16 +000063
Benjamin Kramerd45b2052015-10-07 15:48:01 +000064 // Provide a sane fallback if no VFS is specified.
65 if (!this->VFS)
66 this->VFS = vfs::getRealFileSystem();
67
Sumanth Gundapaneni3a1592942015-03-03 20:43:12 +000068 Name = llvm::sys::path::filename(ClangExecutable);
Douglas Katzmana67e50c2015-06-26 15:47:46 +000069 Dir = llvm::sys::path::parent_path(ClangExecutable);
Benjamin Kramerf420dda2015-10-13 15:19:32 +000070 InstalledDir = Dir; // Provide a sensible default installed dir.
Bob Wilsona20a1da2013-03-23 05:17:59 +000071
72 // Compute the path to the resource directory.
73 StringRef ClangResourceDir(CLANG_RESOURCE_DIR);
74 SmallString<128> P(Dir);
Chandler Carruthfd3cc702014-12-29 12:09:08 +000075 if (ClangResourceDir != "") {
Bob Wilsona20a1da2013-03-23 05:17:59 +000076 llvm::sys::path::append(P, ClangResourceDir);
Chandler Carruthfd3cc702014-12-29 12:09:08 +000077 } else {
78 StringRef ClangLibdirSuffix(CLANG_LIBDIR_SUFFIX);
79 llvm::sys::path::append(P, "..", Twine("lib") + ClangLibdirSuffix, "clang",
80 CLANG_VERSION_STRING);
81 }
Bob Wilsona20a1da2013-03-23 05:17:59 +000082 ResourceDir = P.str();
Daniel Dunbar544ecd12009-03-02 19:59:07 +000083}
84
85Driver::~Driver() {
Daniel Dunbarb2cd66b2009-03-04 20:49:20 +000086 delete Opts;
Chandler Carruth2ad5de12012-01-25 11:01:57 +000087
Reid Kleckner588c9372014-02-19 23:44:52 +000088 llvm::DeleteContainerSeconds(ToolChains);
Daniel Dunbar544ecd12009-03-02 19:59:07 +000089}
90
Zachary Turneraff19c32016-08-12 17:47:52 +000091void Driver::ParseDriverMode(StringRef ProgramName,
92 ArrayRef<const char *> Args) {
93 auto Default = ToolChain::getTargetAndModeFromProgramName(ProgramName);
94 StringRef DefaultMode(Default.second);
95 setDriverModeFromOption(DefaultMode);
Hans Wennborg70850d82013-07-18 20:29:38 +000096
Douglas Katzman6bbffc42015-06-25 18:51:37 +000097 for (const char *ArgPtr : Args) {
Reid Kleckneraf5fd6a2014-08-22 19:29:30 +000098 // Ingore nullptrs, they are response file's EOL markers
Douglas Katzman6bbffc42015-06-25 18:51:37 +000099 if (ArgPtr == nullptr)
Reid Kleckneraf5fd6a2014-08-22 19:29:30 +0000100 continue;
Douglas Katzman6bbffc42015-06-25 18:51:37 +0000101 const StringRef Arg = ArgPtr;
Zachary Turneraff19c32016-08-12 17:47:52 +0000102 setDriverModeFromOption(Arg);
Hans Wennborg70850d82013-07-18 20:29:38 +0000103 }
104}
105
Zachary Turneraff19c32016-08-12 17:47:52 +0000106void Driver::setDriverModeFromOption(StringRef Opt) {
107 const std::string OptName =
108 getOpts().getOption(options::OPT_driver_mode).getPrefixedName();
109 if (!Opt.startswith(OptName))
110 return;
111 StringRef Value = Opt.drop_front(OptName.size());
112
113 const unsigned M = llvm::StringSwitch<unsigned>(Value)
114 .Case("gcc", GCCMode)
115 .Case("g++", GXXMode)
116 .Case("cpp", CPPMode)
117 .Case("cl", CLMode)
118 .Default(~0U);
119
120 if (M != ~0U)
121 Mode = static_cast<DriverMode>(M);
122 else
123 Diag(diag::err_drv_unsupported_option_argument) << OptName << Value;
124}
125
David Blaikie69a1d8c2015-06-22 22:07:27 +0000126InputArgList Driver::ParseArgStrings(ArrayRef<const char *> ArgStrings) {
Daniel Dunbar2608c542009-03-18 01:38:48 +0000127 llvm::PrettyStackTraceString CrashInfo("Command line argument parsing");
Hans Wennborg6ddc6902013-07-27 00:23:45 +0000128
129 unsigned IncludedFlagsBitmask;
130 unsigned ExcludedFlagsBitmask;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +0000131 std::tie(IncludedFlagsBitmask, ExcludedFlagsBitmask) =
Douglas Katzmana67e50c2015-06-26 15:47:46 +0000132 getIncludeExcludeOptionFlagMasks();
Hans Wennborg6ddc6902013-07-27 00:23:45 +0000133
Daniel Dunbar52ed5fe2009-11-19 06:35:06 +0000134 unsigned MissingArgIndex, MissingArgCount;
David Blaikie69a1d8c2015-06-22 22:07:27 +0000135 InputArgList Args =
David Blaikie6d492ad2015-06-21 06:32:36 +0000136 getOpts().ParseArgs(ArgStrings, MissingArgIndex, MissingArgCount,
137 IncludedFlagsBitmask, ExcludedFlagsBitmask);
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +0000138
Daniel Dunbar52ed5fe2009-11-19 06:35:06 +0000139 // Check for missing argument error.
140 if (MissingArgCount)
141 Diag(clang::diag::err_drv_missing_argument)
David Blaikie69a1d8c2015-06-22 22:07:27 +0000142 << Args.getArgString(MissingArgIndex) << MissingArgCount;
Daniel Dunbar65229332009-03-13 11:38:42 +0000143
Daniel Dunbar52ed5fe2009-11-19 06:35:06 +0000144 // Check for unsupported options.
David Blaikie69a1d8c2015-06-22 22:07:27 +0000145 for (const Arg *A : Args) {
Michael J. Spencer66e2b202012-10-19 22:37:06 +0000146 if (A->getOption().hasFlag(options::Unsupported)) {
David Blaikie69a1d8c2015-06-22 22:07:27 +0000147 Diag(clang::diag::err_drv_unsupported_opt) << A->getAsString(Args);
Daniel Dunbard8500f32009-03-22 23:26:43 +0000148 continue;
149 }
Chad Rosierce975d92012-02-22 17:55:22 +0000150
151 // Warn about -mcpu= without an argument.
Douglas Katzmana67e50c2015-06-26 15:47:46 +0000152 if (A->getOption().matches(options::OPT_mcpu_EQ) && A->containsValue("")) {
David Blaikie69a1d8c2015-06-22 22:07:27 +0000153 Diag(clang::diag::warn_drv_empty_joined_argument) << A->getAsString(Args);
Chad Rosierce975d92012-02-22 17:55:22 +0000154 }
Daniel Dunbard02cb1d2009-03-05 06:38:47 +0000155 }
156
David Blaikie69a1d8c2015-06-22 22:07:27 +0000157 for (const Arg *A : Args.filtered(options::OPT_UNKNOWN))
Ehsan Akhgarid8518332016-01-25 21:14:52 +0000158 Diags.Report(IsCLMode() ? diag::warn_drv_unknown_argument_clang_cl :
159 diag::err_drv_unknown_argument)
160 << A->getAsString(Args);
Rafael Espindola8a2d4962013-09-23 23:55:25 +0000161
Daniel Dunbard02cb1d2009-03-05 06:38:47 +0000162 return Args;
163}
164
Chad Rosier7742b5d2011-07-27 23:36:45 +0000165// Determine which compilation mode we are in. We look for options which
166// affect the phase, starting with the earliest phases, and record which
167// option we used to determine the final phase.
Douglas Katzmana67e50c2015-06-26 15:47:46 +0000168phases::ID Driver::getFinalPhase(const DerivedArgList &DAL,
169 Arg **FinalPhaseArg) const {
Craig Topper92fc2df2014-05-17 16:56:41 +0000170 Arg *PhaseArg = nullptr;
Chad Rosier7742b5d2011-07-27 23:36:45 +0000171 phases::ID FinalPhase;
Eric Christopherf901e852011-08-17 22:59:59 +0000172
Hans Wennborge50cec32014-06-13 20:59:54 +0000173 // -{E,EP,P,M,MM} only run the preprocessor.
Douglas Katzmana67e50c2015-06-26 15:47:46 +0000174 if (CCCIsCPP() || (PhaseArg = DAL.getLastArg(options::OPT_E)) ||
Hans Wennborge50cec32014-06-13 20:59:54 +0000175 (PhaseArg = DAL.getLastArg(options::OPT__SLASH_EP)) ||
Hans Wennborge0053472013-12-20 18:40:46 +0000176 (PhaseArg = DAL.getLastArg(options::OPT_M, options::OPT_MM)) ||
177 (PhaseArg = DAL.getLastArg(options::OPT__SLASH_P))) {
Chad Rosier7742b5d2011-07-27 23:36:45 +0000178 FinalPhase = phases::Preprocess;
Eric Christopherf901e852011-08-17 22:59:59 +0000179
Richard Smithdd4ad3d2016-08-30 19:06:26 +0000180 // --precompile only runs up to precompilation.
181 } else if ((PhaseArg = DAL.getLastArg(options::OPT__precompile))) {
182 FinalPhase = phases::Precompile;
183
Bob Wilson23a55f12014-12-21 07:00:00 +0000184 // -{fsyntax-only,-analyze,emit-ast} only run up to the compiler.
Chad Rosier7742b5d2011-07-27 23:36:45 +0000185 } else if ((PhaseArg = DAL.getLastArg(options::OPT_fsyntax_only)) ||
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +0000186 (PhaseArg = DAL.getLastArg(options::OPT_module_file_info)) ||
Ben Langmuir2cb4a782014-02-05 22:21:15 +0000187 (PhaseArg = DAL.getLastArg(options::OPT_verify_pch)) ||
Chad Rosier7742b5d2011-07-27 23:36:45 +0000188 (PhaseArg = DAL.getLastArg(options::OPT_rewrite_objc)) ||
Fariborz Jahanian73223bb2012-04-02 15:59:19 +0000189 (PhaseArg = DAL.getLastArg(options::OPT_rewrite_legacy_objc)) ||
Ted Kremenekf7639e12012-03-06 20:06:33 +0000190 (PhaseArg = DAL.getLastArg(options::OPT__migrate)) ||
Chad Rosier7742b5d2011-07-27 23:36:45 +0000191 (PhaseArg = DAL.getLastArg(options::OPT__analyze,
Chad Rosier1aeb15a2012-03-06 23:14:35 +0000192 options::OPT__analyze_auto)) ||
Bob Wilson23a55f12014-12-21 07:00:00 +0000193 (PhaseArg = DAL.getLastArg(options::OPT_emit_ast))) {
Chad Rosier7742b5d2011-07-27 23:36:45 +0000194 FinalPhase = phases::Compile;
195
Bob Wilson23a55f12014-12-21 07:00:00 +0000196 // -S only runs up to the backend.
197 } else if ((PhaseArg = DAL.getLastArg(options::OPT_S))) {
198 FinalPhase = phases::Backend;
199
Artem Belevich4242f412015-07-28 21:01:21 +0000200 // -c compilation only runs up to the assembler.
201 } else if ((PhaseArg = DAL.getLastArg(options::OPT_c))) {
Chad Rosier7742b5d2011-07-27 23:36:45 +0000202 FinalPhase = phases::Assemble;
203
204 // Otherwise do everything.
205 } else
206 FinalPhase = phases::Link;
207
208 if (FinalPhaseArg)
209 *FinalPhaseArg = PhaseArg;
210
211 return FinalPhase;
212}
213
Douglas Katzmana67e50c2015-06-26 15:47:46 +0000214static Arg *MakeInputArg(DerivedArgList &Args, OptTable *Opts,
Hans Wennborged1d0722013-08-13 21:32:29 +0000215 StringRef Value) {
216 Arg *A = new Arg(Opts->getOption(options::OPT_INPUT), Value,
217 Args.getBaseArgs().MakeIndex(Value), Value.data());
Hans Wennborg55362852014-05-02 22:55:30 +0000218 Args.AddSynthesizedArg(A);
Hans Wennborged1d0722013-08-13 21:32:29 +0000219 A->claim();
220 return A;
221}
222
Daniel Dunbar775d4062010-06-11 22:00:26 +0000223DerivedArgList *Driver::TranslateInputArgs(const InputArgList &Args) const {
224 DerivedArgList *DAL = new DerivedArgList(Args);
225
Daniel Dunbar2cc3f172010-09-17 00:45:02 +0000226 bool HasNostdlib = Args.hasArg(options::OPT_nostdlib);
Nirav Daveb0bb6142015-11-24 16:07:21 +0000227 bool HasNodefaultlib = Args.hasArg(options::OPT_nodefaultlibs);
Saleem Abdulrasool688b6bc2014-12-29 19:01:36 +0000228 for (Arg *A : Args) {
Daniel Dunbarfb3d7472010-06-14 21:23:12 +0000229 // Unfortunately, we have to parse some forwarding options (-Xassembler,
230 // -Xlinker, -Xpreprocessor) because we either integrate their functionality
231 // (assembler and preprocessor), or bypass a previous driver ('collect2').
Daniel Dunbar5a9d1832010-06-14 21:37:09 +0000232
233 // Rewrite linker options, to replace --no-demangle with a custom internal
234 // option.
235 if ((A->getOption().matches(options::OPT_Wl_COMMA) ||
236 A->getOption().matches(options::OPT_Xlinker)) &&
237 A->containsValue("--no-demangle")) {
Daniel Dunbarfb3d7472010-06-14 21:23:12 +0000238 // Add the rewritten no-demangle argument.
239 DAL->AddFlagArg(A, Opts->getOption(options::OPT_Z_Xlinker__no_demangle));
240
241 // Add the remaining values as Xlinker arguments.
Benjamin Kramer72e64312015-09-24 14:48:49 +0000242 for (StringRef Val : A->getValues())
Douglas Katzmana34b7bf2015-06-30 19:32:57 +0000243 if (Val != "--no-demangle")
244 DAL->AddSeparateArg(A, Opts->getOption(options::OPT_Xlinker), Val);
Daniel Dunbarfb3d7472010-06-14 21:23:12 +0000245
246 continue;
247 }
248
Daniel Dunbar5a9d1832010-06-14 21:37:09 +0000249 // Rewrite preprocessor options, to replace -Wp,-MD,FOO which is used by
250 // some build systems. We don't try to be complete here because we don't
251 // care to encourage this usage model.
252 if (A->getOption().matches(options::OPT_Wp_COMMA) &&
Richard Smithbd55daf2012-11-01 04:30:05 +0000253 (A->getValue(0) == StringRef("-MD") ||
254 A->getValue(0) == StringRef("-MMD"))) {
Daniel Dunbar3648ba72010-06-15 20:30:18 +0000255 // Rewrite to -MD/-MMD along with -MF.
Richard Smithbd55daf2012-11-01 04:30:05 +0000256 if (A->getValue(0) == StringRef("-MD"))
Daniel Dunbar3648ba72010-06-15 20:30:18 +0000257 DAL->AddFlagArg(A, Opts->getOption(options::OPT_MD));
258 else
259 DAL->AddFlagArg(A, Opts->getOption(options::OPT_MMD));
Michael J. Spencer70d85be2012-11-07 23:37:14 +0000260 if (A->getNumValues() == 2)
261 DAL->AddSeparateArg(A, Opts->getOption(options::OPT_MF),
262 A->getValue(1));
Daniel Dunbar5a9d1832010-06-14 21:37:09 +0000263 continue;
264 }
265
Shantonu Senafeb03b2010-09-17 18:39:08 +0000266 // Rewrite reserved library names.
267 if (A->getOption().matches(options::OPT_l)) {
Richard Smithbd55daf2012-11-01 04:30:05 +0000268 StringRef Value = A->getValue();
Daniel Dunbar2cc3f172010-09-17 00:45:02 +0000269
Shantonu Senafeb03b2010-09-17 18:39:08 +0000270 // Rewrite unless -nostdlib is present.
Nirav Daveb0bb6142015-11-24 16:07:21 +0000271 if (!HasNostdlib && !HasNodefaultlib && Value == "stdc++") {
Douglas Katzmana67e50c2015-06-26 15:47:46 +0000272 DAL->AddFlagArg(A, Opts->getOption(options::OPT_Z_reserved_lib_stdcxx));
Daniel Dunbar2cc3f172010-09-17 00:45:02 +0000273 continue;
274 }
Shantonu Senafeb03b2010-09-17 18:39:08 +0000275
276 // Rewrite unconditionally.
277 if (Value == "cc_kext") {
Douglas Katzmana67e50c2015-06-26 15:47:46 +0000278 DAL->AddFlagArg(A, Opts->getOption(options::OPT_Z_reserved_lib_cckext));
Shantonu Senafeb03b2010-09-17 18:39:08 +0000279 continue;
280 }
Daniel Dunbar2cc3f172010-09-17 00:45:02 +0000281 }
282
Hans Wennborged1d0722013-08-13 21:32:29 +0000283 // Pick up inputs via the -- option.
284 if (A->getOption().matches(options::OPT__DASH_DASH)) {
285 A->claim();
Benjamin Kramer72e64312015-09-24 14:48:49 +0000286 for (StringRef Val : A->getValues())
Douglas Katzmana34b7bf2015-06-30 19:32:57 +0000287 DAL->append(MakeInputArg(*DAL, Opts, Val));
Hans Wennborged1d0722013-08-13 21:32:29 +0000288 continue;
289 }
290
Saleem Abdulrasool688b6bc2014-12-29 19:01:36 +0000291 DAL->append(A);
Daniel Dunbarfb3d7472010-06-14 21:23:12 +0000292 }
Daniel Dunbar775d4062010-06-11 22:00:26 +0000293
Andrey Turetskiy6a8b91d2016-04-21 10:16:48 +0000294 // Enforce -static if -miamcu is present.
Andrey Turetskiy5fea71c2016-06-29 10:57:17 +0000295 if (Args.hasFlag(options::OPT_miamcu, options::OPT_mno_iamcu, false))
296 DAL->AddFlagArg(0, Opts->getOption(options::OPT_static));
Andrey Turetskiy6a8b91d2016-04-21 10:16:48 +0000297
Douglas Katzmana67e50c2015-06-26 15:47:46 +0000298// Add a default value of -mlinker-version=, if one was given and the user
299// didn't specify one.
Daniel Dunbar628fcf42010-08-12 00:05:12 +0000300#if defined(HOST_LINK_VERSION)
Tim Northover018578c2015-06-12 19:21:35 +0000301 if (!Args.hasArg(options::OPT_mlinker_version_EQ) &&
302 strlen(HOST_LINK_VERSION) > 0) {
Daniel Dunbar628fcf42010-08-12 00:05:12 +0000303 DAL->AddJoinedArg(0, Opts->getOption(options::OPT_mlinker_version_EQ),
304 HOST_LINK_VERSION);
Daniel Dunbarb613ffc2010-08-17 22:32:45 +0000305 DAL->getLastArg(options::OPT_mlinker_version_EQ)->claim();
Daniel Dunbar628fcf42010-08-12 00:05:12 +0000306 }
307#endif
308
Daniel Dunbar775d4062010-06-11 22:00:26 +0000309 return DAL;
310}
311
Artem Belevich959e0542015-07-10 19:47:55 +0000312/// \brief Compute target triple from args.
313///
314/// This routine provides the logic to compute a target triple from various
315/// args passed to the driver and the default triple string.
Andrey Turetskiy6a8b91d2016-04-21 10:16:48 +0000316static llvm::Triple computeTargetTriple(const Driver &D,
317 StringRef DefaultTargetTriple,
Artem Belevich959e0542015-07-10 19:47:55 +0000318 const ArgList &Args,
319 StringRef DarwinArchName = "") {
320 // FIXME: Already done in Compilation *Driver::BuildCompilation
321 if (const Arg *A = Args.getLastArg(options::OPT_target))
322 DefaultTargetTriple = A->getValue();
323
324 llvm::Triple Target(llvm::Triple::normalize(DefaultTargetTriple));
325
326 // Handle Apple-specific options available here.
327 if (Target.isOSBinFormatMachO()) {
328 // If an explict Darwin arch name is given, that trumps all.
329 if (!DarwinArchName.empty()) {
330 tools::darwin::setTripleTypeForMachOArchName(Target, DarwinArchName);
331 return Target;
332 }
333
334 // Handle the Darwin '-arch' flag.
335 if (Arg *A = Args.getLastArg(options::OPT_arch)) {
336 StringRef ArchName = A->getValue();
337 tools::darwin::setTripleTypeForMachOArchName(Target, ArchName);
338 }
339 }
340
341 // Handle pseudo-target flags '-mlittle-endian'/'-EL' and
342 // '-mbig-endian'/'-EB'.
343 if (Arg *A = Args.getLastArg(options::OPT_mlittle_endian,
344 options::OPT_mbig_endian)) {
345 if (A->getOption().matches(options::OPT_mlittle_endian)) {
346 llvm::Triple LE = Target.getLittleEndianArchVariant();
347 if (LE.getArch() != llvm::Triple::UnknownArch)
348 Target = std::move(LE);
349 } else {
350 llvm::Triple BE = Target.getBigEndianArchVariant();
351 if (BE.getArch() != llvm::Triple::UnknownArch)
352 Target = std::move(BE);
353 }
354 }
355
356 // Skip further flag support on OSes which don't support '-m32' or '-m64'.
Douglas Katzman15a63ed2015-08-12 18:36:12 +0000357 if (Target.getArch() == llvm::Triple::tce ||
358 Target.getOS() == llvm::Triple::Minix)
Artem Belevich959e0542015-07-10 19:47:55 +0000359 return Target;
360
361 // Handle pseudo-target flags '-m64', '-mx32', '-m32' and '-m16'.
Andrey Turetskiy6a8b91d2016-04-21 10:16:48 +0000362 Arg *A = Args.getLastArg(options::OPT_m64, options::OPT_mx32,
363 options::OPT_m32, options::OPT_m16);
364 if (A) {
Artem Belevich959e0542015-07-10 19:47:55 +0000365 llvm::Triple::ArchType AT = llvm::Triple::UnknownArch;
366
367 if (A->getOption().matches(options::OPT_m64)) {
368 AT = Target.get64BitArchVariant().getArch();
369 if (Target.getEnvironment() == llvm::Triple::GNUX32)
370 Target.setEnvironment(llvm::Triple::GNU);
371 } else if (A->getOption().matches(options::OPT_mx32) &&
372 Target.get64BitArchVariant().getArch() == llvm::Triple::x86_64) {
373 AT = llvm::Triple::x86_64;
374 Target.setEnvironment(llvm::Triple::GNUX32);
375 } else if (A->getOption().matches(options::OPT_m32)) {
376 AT = Target.get32BitArchVariant().getArch();
377 if (Target.getEnvironment() == llvm::Triple::GNUX32)
378 Target.setEnvironment(llvm::Triple::GNU);
379 } else if (A->getOption().matches(options::OPT_m16) &&
380 Target.get32BitArchVariant().getArch() == llvm::Triple::x86) {
381 AT = llvm::Triple::x86;
382 Target.setEnvironment(llvm::Triple::CODE16);
383 }
384
385 if (AT != llvm::Triple::UnknownArch && AT != Target.getArch())
386 Target.setArch(AT);
387 }
388
Andrey Turetskiy6a8b91d2016-04-21 10:16:48 +0000389 // Handle -miamcu flag.
Andrey Turetskiy5fea71c2016-06-29 10:57:17 +0000390 if (Args.hasFlag(options::OPT_miamcu, options::OPT_mno_iamcu, false)) {
391 if (Target.get32BitArchVariant().getArch() != llvm::Triple::x86)
392 D.Diag(diag::err_drv_unsupported_opt_for_target) << "-miamcu"
393 << Target.str();
Andrey Turetskiy6a8b91d2016-04-21 10:16:48 +0000394
Andrey Turetskiy5fea71c2016-06-29 10:57:17 +0000395 if (A && !A->getOption().matches(options::OPT_m32))
396 D.Diag(diag::err_drv_argument_not_allowed_with)
397 << "-miamcu" << A->getBaseArg().getAsString(Args);
Andrey Turetskiy6a8b91d2016-04-21 10:16:48 +0000398
Andrey Turetskiy5fea71c2016-06-29 10:57:17 +0000399 Target.setArch(llvm::Triple::x86);
400 Target.setArchName("i586");
401 Target.setEnvironment(llvm::Triple::UnknownEnvironment);
402 Target.setEnvironmentName("");
403 Target.setOS(llvm::Triple::ELFIAMCU);
404 Target.setVendor(llvm::Triple::UnknownVendor);
405 Target.setVendorName("intel");
Andrey Turetskiy6a8b91d2016-04-21 10:16:48 +0000406 }
407
Artem Belevich959e0542015-07-10 19:47:55 +0000408 return Target;
409}
410
Teresa Johnson945bc502015-10-15 20:35:53 +0000411// \brief Parse the LTO options and record the type of LTO compilation
412// based on which -f(no-)?lto(=.*)? option occurs last.
413void Driver::setLTOMode(const llvm::opt::ArgList &Args) {
414 LTOMode = LTOK_None;
415 if (!Args.hasFlag(options::OPT_flto, options::OPT_flto_EQ,
416 options::OPT_fno_lto, false))
417 return;
418
419 StringRef LTOName("full");
420
421 const Arg *A = Args.getLastArg(options::OPT_flto_EQ);
Teresa Johnson6ef80dc2015-11-02 18:03:12 +0000422 if (A)
423 LTOName = A->getValue();
Teresa Johnson945bc502015-10-15 20:35:53 +0000424
425 LTOMode = llvm::StringSwitch<LTOKind>(LTOName)
426 .Case("full", LTOK_Full)
427 .Case("thin", LTOK_Thin)
428 .Default(LTOK_Unknown);
429
430 if (LTOMode == LTOK_Unknown) {
431 assert(A);
432 Diag(diag::err_drv_unsupported_option_argument) << A->getOption().getName()
433 << A->getValue();
434 }
435}
436
Samuel Antao39f9da22016-10-27 16:38:05 +0000437/// Compute the desired OpenMP runtime from the flags provided.
438Driver::OpenMPRuntimeKind Driver::getOpenMPRuntime(const ArgList &Args) const {
439 StringRef RuntimeName(CLANG_DEFAULT_OPENMP_RUNTIME);
440
441 const Arg *A = Args.getLastArg(options::OPT_fopenmp_EQ);
442 if (A)
443 RuntimeName = A->getValue();
444
445 auto RT = llvm::StringSwitch<OpenMPRuntimeKind>(RuntimeName)
446 .Case("libomp", OMPRT_OMP)
447 .Case("libgomp", OMPRT_GOMP)
448 .Case("libiomp5", OMPRT_IOMP5)
449 .Default(OMPRT_Unknown);
450
451 if (RT == OMPRT_Unknown) {
452 if (A)
453 Diag(diag::err_drv_unsupported_option_argument)
454 << A->getOption().getName() << A->getValue();
455 else
456 // FIXME: We could use a nicer diagnostic here.
457 Diag(diag::err_drv_unsupported_opt) << "-fopenmp";
458 }
459
460 return RT;
461}
462
Samuel Antaoc1ffba52016-06-13 18:10:57 +0000463void Driver::CreateOffloadingDeviceToolChains(Compilation &C,
464 InputList &Inputs) {
465
466 //
467 // CUDA
468 //
469 // We need to generate a CUDA toolchain if any of the inputs has a CUDA type.
470 if (llvm::any_of(Inputs, [](std::pair<types::ID, const llvm::opt::Arg *> &I) {
471 return types::isCuda(I.first);
472 })) {
473 const ToolChain &TC = getToolChain(
474 C.getInputArgs(),
Samuel Antaod06239d2016-07-15 23:13:27 +0000475 llvm::Triple(C.getSingleOffloadToolChain<Action::OFK_Host>()
476 ->getTriple()
477 .isArch64Bit()
Samuel Antaoc1ffba52016-06-13 18:10:57 +0000478 ? "nvptx64-nvidia-cuda"
479 : "nvptx-nvidia-cuda"));
480 C.addOffloadDeviceToolChain(&TC, Action::OFK_Cuda);
481 }
482
483 //
Samuel Antao39f9da22016-10-27 16:38:05 +0000484 // OpenMP
485 //
486 // We need to generate an OpenMP toolchain if the user specified targets with
487 // the -fopenmp-targets option.
488 if (Arg *OpenMPTargets =
489 C.getInputArgs().getLastArg(options::OPT_fopenmp_targets_EQ)) {
490 if (OpenMPTargets->getNumValues()) {
491 // We expect that -fopenmp-targets is always used in conjunction with the
492 // option -fopenmp specifying a valid runtime with offloading support,
493 // i.e. libomp or libiomp.
494 bool HasValidOpenMPRuntime = C.getInputArgs().hasFlag(
495 options::OPT_fopenmp, options::OPT_fopenmp_EQ,
496 options::OPT_fno_openmp, false);
497 if (HasValidOpenMPRuntime) {
498 OpenMPRuntimeKind OpenMPKind = getOpenMPRuntime(C.getInputArgs());
499 HasValidOpenMPRuntime =
500 OpenMPKind == OMPRT_OMP || OpenMPKind == OMPRT_IOMP5;
501 }
502
503 if (HasValidOpenMPRuntime) {
504 llvm::StringMap<const char *> FoundNormalizedTriples;
505 for (const char *Val : OpenMPTargets->getValues()) {
506 llvm::Triple TT(Val);
507 std::string NormalizedName = TT.normalize();
508
509 // Make sure we don't have a duplicate triple.
510 auto Duplicate = FoundNormalizedTriples.find(NormalizedName);
511 if (Duplicate != FoundNormalizedTriples.end()) {
512 Diag(clang::diag::warn_drv_omp_offload_target_duplicate)
513 << Val << Duplicate->second;
514 continue;
515 }
516
517 // Store the current triple so that we can check for duplicates in the
518 // following iterations.
519 FoundNormalizedTriples[NormalizedName] = Val;
520
521 // If the specified target is invalid, emit a diagnostic.
522 if (TT.getArch() == llvm::Triple::UnknownArch)
523 Diag(clang::diag::err_drv_invalid_omp_target) << Val;
524 else {
525 const ToolChain &TC = getToolChain(C.getInputArgs(), TT);
526 C.addOffloadDeviceToolChain(&TC, Action::OFK_OpenMP);
527 }
528 }
529 } else
530 Diag(clang::diag::err_drv_expecting_fopenmp_with_fopenmp_targets);
531 } else
532 Diag(clang::diag::warn_drv_empty_joined_argument)
533 << OpenMPTargets->getAsString(C.getInputArgs());
534 }
535
536 //
Samuel Antaoc1ffba52016-06-13 18:10:57 +0000537 // TODO: Add support for other offloading programming models here.
538 //
539
540 return;
541}
542
Chris Lattner54b16772011-07-23 17:14:25 +0000543Compilation *Driver::BuildCompilation(ArrayRef<const char *> ArgList) {
Daniel Dunbar2608c542009-03-18 01:38:48 +0000544 llvm::PrettyStackTraceString CrashInfo("Compilation construction");
545
Eric Christopherf901e852011-08-17 22:59:59 +0000546 // FIXME: Handle environment options which affect driver behavior, somewhere
Bill Wendlingadbeb9f2012-03-12 21:24:57 +0000547 // (client?). GCC_EXEC_PREFIX, LPATH, CC_PRINT_OPTIONS.
Chad Rosier82301162011-09-14 00:47:55 +0000548
David Majnemer85c25b42016-07-24 17:44:03 +0000549 if (Optional<std::string> CompilerPathValue =
550 llvm::sys::Process::GetEnv("COMPILER_PATH")) {
551 StringRef CompilerPath = *CompilerPathValue;
Chad Rosier82301162011-09-14 00:47:55 +0000552 while (!CompilerPath.empty()) {
Douglas Katzmana67e50c2015-06-26 15:47:46 +0000553 std::pair<StringRef, StringRef> Split =
554 CompilerPath.split(llvm::sys::EnvPathSeparator);
Chad Rosier82301162011-09-14 00:47:55 +0000555 PrefixDirs.push_back(Split.first);
556 CompilerPath = Split.second;
557 }
558 }
Daniel Dunbar5e0f6af2009-03-13 00:51:18 +0000559
Hans Wennborg70850d82013-07-18 20:29:38 +0000560 // We look for the driver mode option early, because the mode can affect
561 // how other options are parsed.
Zachary Turneraff19c32016-08-12 17:47:52 +0000562 ParseDriverMode(ClangExecutable, ArgList.slice(1));
Hans Wennborg70850d82013-07-18 20:29:38 +0000563
Daniel Dunbar5e0f6af2009-03-13 00:51:18 +0000564 // FIXME: What are we going to do with -V and -b?
565
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +0000566 // FIXME: This stuff needs to go into the Compilation, not the driver.
Douglas Katzmanb7e8ef02015-06-25 19:37:41 +0000567 bool CCCPrintPhases;
Daniel Dunbard02cb1d2009-03-05 06:38:47 +0000568
David Blaikie69a1d8c2015-06-22 22:07:27 +0000569 InputArgList Args = ParseArgStrings(ArgList.slice(1));
Daniel Dunbaracd69572009-12-04 21:55:23 +0000570
Filipe Cabecinhas136f35e2015-07-18 06:35:24 +0000571 // Silence driver warnings if requested
572 Diags.setIgnoreAllWarnings(Args.hasArg(options::OPT_w));
573
Rafael Espindola59ae7992009-12-07 18:28:29 +0000574 // -no-canonical-prefixes is used very early in main.
David Blaikie69a1d8c2015-06-22 22:07:27 +0000575 Args.ClaimAllArgs(options::OPT_no_canonical_prefixes);
Rafael Espindola59ae7992009-12-07 18:28:29 +0000576
Daniel Dunbar926f81f2010-08-02 02:38:03 +0000577 // Ignore -pipe.
David Blaikie69a1d8c2015-06-22 22:07:27 +0000578 Args.ClaimAllArgs(options::OPT_pipe);
Daniel Dunbar926f81f2010-08-02 02:38:03 +0000579
Daniel Dunbaracd69572009-12-04 21:55:23 +0000580 // Extract -ccc args.
Daniel Dunbaree66cf22009-03-10 20:52:46 +0000581 //
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +0000582 // FIXME: We need to figure out where this behavior should live. Most of it
583 // should be outside in the client; the parts that aren't should have proper
584 // options, either by introducing new ones or by overloading gcc ones like -V
585 // or -b.
Douglas Katzmanb7e8ef02015-06-25 19:37:41 +0000586 CCCPrintPhases = Args.hasArg(options::OPT_ccc_print_phases);
David Blaikie69a1d8c2015-06-22 22:07:27 +0000587 CCCPrintBindings = Args.hasArg(options::OPT_ccc_print_bindings);
588 if (const Arg *A = Args.getLastArg(options::OPT_ccc_gcc_name))
Richard Smithbd55daf2012-11-01 04:30:05 +0000589 CCCGenericGCCName = A->getValue();
David Blaikie69a1d8c2015-06-22 22:07:27 +0000590 CCCUsePCH =
591 Args.hasFlag(options::OPT_ccc_pch_is_pch, options::OPT_ccc_pch_is_pth);
Joerg Sonnenberger17d75512012-02-22 19:15:16 +0000592 // FIXME: DefaultTargetTriple is used by the target-prefixed calls to as/ld
593 // and getToolChain is const.
Hans Wennborg2e274592013-08-13 23:38:57 +0000594 if (IsCLMode()) {
Hans Wennborg73609a02014-03-28 01:19:04 +0000595 // clang-cl targets MSVC-style Win32.
Hans Wennborg2e274592013-08-13 23:38:57 +0000596 llvm::Triple T(DefaultTargetTriple);
Hans Wennborg9d9ce7a2014-03-28 20:49:28 +0000597 T.setOS(llvm::Triple::Win32);
Hans Wennborg0f0e8d62015-09-18 17:11:50 +0000598 T.setVendor(llvm::Triple::PC);
Hans Wennborg9d9ce7a2014-03-28 20:49:28 +0000599 T.setEnvironment(llvm::Triple::MSVC);
Hans Wennborg2e274592013-08-13 23:38:57 +0000600 DefaultTargetTriple = T.str();
601 }
David Blaikie69a1d8c2015-06-22 22:07:27 +0000602 if (const Arg *A = Args.getLastArg(options::OPT_target))
Richard Smithbd55daf2012-11-01 04:30:05 +0000603 DefaultTargetTriple = A->getValue();
David Blaikie69a1d8c2015-06-22 22:07:27 +0000604 if (const Arg *A = Args.getLastArg(options::OPT_ccc_install_dir))
Richard Smithbd55daf2012-11-01 04:30:05 +0000605 Dir = InstalledDir = A->getValue();
David Blaikie69a1d8c2015-06-22 22:07:27 +0000606 for (const Arg *A : Args.filtered(options::OPT_B)) {
Benjamin Kramer1a648d12011-02-08 20:31:42 +0000607 A->claim();
Richard Smithbd55daf2012-11-01 04:30:05 +0000608 PrefixDirs.push_back(A->getValue(0));
Benjamin Kramer1a648d12011-02-08 20:31:42 +0000609 }
David Blaikie69a1d8c2015-06-22 22:07:27 +0000610 if (const Arg *A = Args.getLastArg(options::OPT__sysroot_EQ))
Richard Smithbd55daf2012-11-01 04:30:05 +0000611 SysRoot = A->getValue();
David Blaikie69a1d8c2015-06-22 22:07:27 +0000612 if (const Arg *A = Args.getLastArg(options::OPT__dyld_prefix_EQ))
Peter Collingbourne9d9e1fc2013-05-27 21:40:20 +0000613 DyldPrefix = A->getValue();
David Blaikie69a1d8c2015-06-22 22:07:27 +0000614 if (Args.hasArg(options::OPT_nostdlib))
Joerg Sonnenbergerbc923f32011-03-21 13:59:26 +0000615 UseStdLib = false;
Daniel Dunbaree66cf22009-03-10 20:52:46 +0000616
David Blaikie69a1d8c2015-06-22 22:07:27 +0000617 if (const Arg *A = Args.getLastArg(options::OPT_resource_dir))
Bob Wilsona20a1da2013-03-23 05:17:59 +0000618 ResourceDir = A->getValue();
Jim Grosbach061dabf2013-03-12 20:17:58 +0000619
David Blaikie69a1d8c2015-06-22 22:07:27 +0000620 if (const Arg *A = Args.getLastArg(options::OPT_save_temps_EQ)) {
Reid Kleckner68eb60b2015-02-02 22:41:48 +0000621 SaveTemps = llvm::StringSwitch<SaveTempsMode>(A->getValue())
622 .Case("cwd", SaveTempsCwd)
623 .Case("obj", SaveTempsObj)
624 .Default(SaveTempsCwd);
625 }
626
Steven Wu1257cd82016-05-18 17:04:52 +0000627 setLTOMode(Args);
628
Steven Wu574b0f22016-03-01 01:07:58 +0000629 // Ignore -fembed-bitcode options with LTO
630 // since the output will be bitcode anyway.
Steven Wu1257cd82016-05-18 17:04:52 +0000631 if (getLTOMode() == LTOK_None) {
Steven Wu27fb5222016-05-11 16:26:03 +0000632 if (Arg *A = Args.getLastArg(options::OPT_fembed_bitcode_EQ)) {
633 StringRef Name = A->getValue();
634 unsigned Model = llvm::StringSwitch<unsigned>(Name)
635 .Case("off", EmbedNone)
636 .Case("all", EmbedBitcode)
637 .Case("bitcode", EmbedBitcode)
638 .Case("marker", EmbedMarker)
639 .Default(~0U);
640 if (Model == ~0U) {
641 Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args)
642 << Name;
643 } else
644 BitcodeEmbed = static_cast<BitcodeEmbedMode>(Model);
645 }
Steven Wu574b0f22016-03-01 01:07:58 +0000646 } else {
647 // claim the bitcode option under LTO so no warning is issued.
Steven Wu27fb5222016-05-11 16:26:03 +0000648 Args.ClaimAllArgs(options::OPT_fembed_bitcode_EQ);
Steven Wu574b0f22016-03-01 01:07:58 +0000649 }
650
David Blaikie69a1d8c2015-06-22 22:07:27 +0000651 std::unique_ptr<llvm::opt::InputArgList> UArgs =
652 llvm::make_unique<InputArgList>(std::move(Args));
653
Daniel Dunbar775d4062010-06-11 22:00:26 +0000654 // Perform the default argument translations.
David Blaikie69a1d8c2015-06-22 22:07:27 +0000655 DerivedArgList *TranslatedArgs = TranslateInputArgs(*UArgs);
Daniel Dunbar775d4062010-06-11 22:00:26 +0000656
Chandler Carruthcb916192012-01-25 08:49:21 +0000657 // Owned by the host.
Andrey Turetskiy6a8b91d2016-04-21 10:16:48 +0000658 const ToolChain &TC = getToolChain(
659 *UArgs, computeTargetTriple(*this, DefaultTargetTriple, *UArgs));
Chandler Carruthcb916192012-01-25 08:49:21 +0000660
Daniel Dunbar3ce436d2009-03-16 06:42:30 +0000661 // The compilation takes ownership of Args.
David Blaikie69a1d8c2015-06-22 22:07:27 +0000662 Compilation *C = new Compilation(*this, TC, UArgs.release(), TranslatedArgs);
Daniel Dunbarf0eddb82009-03-18 02:55:38 +0000663
Daniel Dunbarf0eddb82009-03-18 02:55:38 +0000664 if (!HandleImmediateArgs(*C))
665 return C;
666
Chad Rosierecdede82011-08-12 22:08:57 +0000667 // Construct the list of inputs.
668 InputList Inputs;
Hans Wennborged1d0722013-08-13 21:32:29 +0000669 BuildInputs(C->getDefaultToolChain(), *TranslatedArgs, Inputs);
Chad Rosierecdede82011-08-12 22:08:57 +0000670
Samuel Antaoc1ffba52016-06-13 18:10:57 +0000671 // Populate the tool chains for the offloading devices, if any.
672 CreateOffloadingDeviceToolChains(*C, Inputs);
Justin Lebar0e450a52016-03-30 23:30:25 +0000673
Chandler Carruth7f1417f2012-01-24 10:43:44 +0000674 // Construct the list of abstract actions to perform for this compilation. On
Tim Northover157d9112014-01-16 08:48:16 +0000675 // MachO targets this uses the driver-driver and universal actions.
676 if (TC.getTriple().isOSBinFormatMachO())
Artem Belevich5e2a3ec2015-11-17 22:28:40 +0000677 BuildUniversalActions(*C, C->getDefaultToolChain(), Inputs);
Daniel Dunbarf0eddb82009-03-18 02:55:38 +0000678 else
Justin Lebar0f3474c2016-02-11 02:00:50 +0000679 BuildActions(*C, C->getArgs(), Inputs, C->getActions());
Daniel Dunbarf0eddb82009-03-18 02:55:38 +0000680
Douglas Katzmanb7e8ef02015-06-25 19:37:41 +0000681 if (CCCPrintPhases) {
Daniel Dunbareb843be2009-03-18 03:13:20 +0000682 PrintActions(*C);
Daniel Dunbarf0eddb82009-03-18 02:55:38 +0000683 return C;
684 }
685
686 BuildJobs(*C);
Daniel Dunbaradc91e62009-03-15 01:38:15 +0000687
688 return C;
Daniel Dunbaree66cf22009-03-10 20:52:46 +0000689}
690
Justin Bognered9cbe02015-07-09 06:58:31 +0000691static void printArgList(raw_ostream &OS, const llvm::opt::ArgList &Args) {
692 llvm::opt::ArgStringList ASL;
693 for (const auto *A : Args)
694 A->render(Args, ASL);
695
696 for (auto I = ASL.begin(), E = ASL.end(); I != E; ++I) {
697 if (I != ASL.begin())
698 OS << ' ';
699 Command::printArg(OS, *I, true);
700 }
701 OS << '\n';
702}
703
Eric Christopherf901e852011-08-17 22:59:59 +0000704// When clang crashes, produce diagnostic information including the fully
705// preprocessed source file(s). Request that the developer attach the
Chad Rosierbe10f982011-08-02 17:58:04 +0000706// diagnostic information to a bug report.
707void Driver::generateCompilationDiagnostics(Compilation &C,
Justin Bognere1a33d12014-10-20 21:02:05 +0000708 const Command &FailingCommand) {
Chad Rosier877c0a22012-02-22 00:30:39 +0000709 if (C.getArgs().hasArg(options::OPT_fno_crash_diagnostics))
Chad Rosier62135492012-07-09 17:31:28 +0000710 return;
Chad Rosierbee5a1d2012-03-07 00:30:40 +0000711
Chad Rosierdbf46a12013-02-01 18:30:26 +0000712 // Don't try to generate diagnostics for link or dsymutil jobs.
Justin Bognere1a33d12014-10-20 21:02:05 +0000713 if (FailingCommand.getCreator().isLinkJob() ||
714 FailingCommand.getCreator().isDsymutilJob())
Chad Rosier877c0a22012-02-22 00:30:39 +0000715 return;
716
Chad Rosier8179f112012-06-19 17:51:34 +0000717 // Print the version of the compiler.
718 PrintVersion(C, llvm::errs());
719
Chad Rosierbe10f982011-08-02 17:58:04 +0000720 Diag(clang::diag::note_drv_command_failed_diag_msg)
Douglas Katzmana67e50c2015-06-26 15:47:46 +0000721 << "PLEASE submit a bug report to " BUG_REPORT_URL " and include the "
722 "crash backtrace, preprocessed source, and associated run script.";
Chad Rosierbe10f982011-08-02 17:58:04 +0000723
724 // Suppress driver output and emit preprocessor output to temp file.
Hans Wennborg70850d82013-07-18 20:29:38 +0000725 Mode = CPPMode;
Chad Rosierbe10f982011-08-02 17:58:04 +0000726 CCGenDiagnostics = true;
727
Chad Rosiercdb008d2011-11-02 21:29:05 +0000728 // Save the original job command(s).
Justin Bogner25645152014-10-21 17:24:44 +0000729 Command Cmd = FailingCommand;
Chad Rosiercdb008d2011-11-02 21:29:05 +0000730
Richard Smith5bb4cdf2012-12-20 02:22:15 +0000731 // Keep track of whether we produce any errors while trying to produce
732 // preprocessed sources.
733 DiagnosticErrorTrap Trap(Diags);
734
735 // Suppress tool output.
Chad Rosierbe10f982011-08-02 17:58:04 +0000736 C.initCompilationForDiagnostics();
Chad Rosierecdede82011-08-12 22:08:57 +0000737
738 // Construct the list of inputs.
739 InputList Inputs;
740 BuildInputs(C.getDefaultToolChain(), C.getArgs(), Inputs);
Chad Rosierbe10f982011-08-02 17:58:04 +0000741
Chad Rosier4f81fc22011-08-12 23:30:05 +0000742 for (InputList::iterator it = Inputs.begin(), ie = Inputs.end(); it != ie;) {
Chad Rosierd57133d2011-08-18 00:22:25 +0000743 bool IgnoreInput = false;
744
745 // Ignore input from stdin or any inputs that cannot be preprocessed.
Paul Robinsonf44157d2014-04-28 22:24:44 +0000746 // Check type first as not all linker inputs have a value.
Douglas Katzmana67e50c2015-06-26 15:47:46 +0000747 if (types::getPreprocessedType(it->first) == types::TY_INVALID) {
Paul Robinsonf44157d2014-04-28 22:24:44 +0000748 IgnoreInput = true;
749 } else if (!strcmp(it->second->getValue(), "-")) {
Chad Rosierd57133d2011-08-18 00:22:25 +0000750 Diag(clang::diag::note_drv_command_failed_diag_msg)
Douglas Katzmana67e50c2015-06-26 15:47:46 +0000751 << "Error generating preprocessed source(s) - "
752 "ignoring input from stdin.";
Chad Rosierd57133d2011-08-18 00:22:25 +0000753 IgnoreInput = true;
Chad Rosierd57133d2011-08-18 00:22:25 +0000754 }
755
756 if (IgnoreInput) {
Chad Rosier4f81fc22011-08-12 23:30:05 +0000757 it = Inputs.erase(it);
758 ie = Inputs.end();
Chad Rosier6fdf38b2011-08-17 23:08:45 +0000759 } else {
Chad Rosier4f81fc22011-08-12 23:30:05 +0000760 ++it;
Chad Rosier6fdf38b2011-08-17 23:08:45 +0000761 }
Chad Rosier4f81fc22011-08-12 23:30:05 +0000762 }
Chad Rosierd57133d2011-08-18 00:22:25 +0000763
Chad Rosierc5103c32013-01-29 23:57:10 +0000764 if (Inputs.empty()) {
765 Diag(clang::diag::note_drv_command_failed_diag_msg)
Douglas Katzmana67e50c2015-06-26 15:47:46 +0000766 << "Error generating preprocessed source(s) - "
767 "no preprocessable inputs.";
Chad Rosierc5103c32013-01-29 23:57:10 +0000768 return;
769 }
770
Chad Rosiere75ef402011-09-06 23:52:36 +0000771 // Don't attempt to generate preprocessed files if multiple -arch options are
Chad Rosier636d2832012-02-13 18:16:28 +0000772 // used, unless they're all duplicates.
773 llvm::StringSet<> ArchNames;
Saleem Abdulrasool688b6bc2014-12-29 19:01:36 +0000774 for (const Arg *A : C.getArgs()) {
Chad Rosiere75ef402011-09-06 23:52:36 +0000775 if (A->getOption().matches(options::OPT_arch)) {
Richard Smithbd55daf2012-11-01 04:30:05 +0000776 StringRef ArchName = A->getValue();
Chad Rosier636d2832012-02-13 18:16:28 +0000777 ArchNames.insert(ArchName);
Chad Rosiere75ef402011-09-06 23:52:36 +0000778 }
779 }
Chad Rosier636d2832012-02-13 18:16:28 +0000780 if (ArchNames.size() > 1) {
781 Diag(clang::diag::note_drv_command_failed_diag_msg)
Douglas Katzmana67e50c2015-06-26 15:47:46 +0000782 << "Error generating preprocessed source(s) - cannot generate "
783 "preprocessed source with multiple -arch options.";
Chad Rosier636d2832012-02-13 18:16:28 +0000784 return;
785 }
Chad Rosiere75ef402011-09-06 23:52:36 +0000786
Chandler Carruth7f1417f2012-01-24 10:43:44 +0000787 // Construct the list of abstract actions to perform for this compilation. On
788 // Darwin OSes this uses the driver-driver and builds universal actions.
Chandler Carruthcb916192012-01-25 08:49:21 +0000789 const ToolChain &TC = C.getDefaultToolChain();
Tim Northover157d9112014-01-16 08:48:16 +0000790 if (TC.getTriple().isOSBinFormatMachO())
Artem Belevich5e2a3ec2015-11-17 22:28:40 +0000791 BuildUniversalActions(C, TC, Inputs);
Chad Rosierbe10f982011-08-02 17:58:04 +0000792 else
Justin Lebar0f3474c2016-02-11 02:00:50 +0000793 BuildActions(C, C.getArgs(), Inputs, C.getActions());
Chad Rosierbe10f982011-08-02 17:58:04 +0000794
795 BuildJobs(C);
796
797 // If there were errors building the compilation, quit now.
Richard Smith5bb4cdf2012-12-20 02:22:15 +0000798 if (Trap.hasErrorOccurred()) {
Chad Rosierbe10f982011-08-02 17:58:04 +0000799 Diag(clang::diag::note_drv_command_failed_diag_msg)
Douglas Katzmana67e50c2015-06-26 15:47:46 +0000800 << "Error generating preprocessed source(s).";
Chad Rosierbe10f982011-08-02 17:58:04 +0000801 return;
802 }
803
804 // Generate preprocessed output.
Chad Rosierdd60e092013-01-29 20:15:05 +0000805 SmallVector<std::pair<int, const Command *>, 4> FailingCommands;
Justin Bogner0cd92482015-07-02 22:52:08 +0000806 C.ExecuteJobs(C.getJobs(), FailingCommands);
Chad Rosierbe10f982011-08-02 17:58:04 +0000807
Justin Bognerbc89b182014-10-20 21:20:27 +0000808 // If any of the preprocessing commands failed, clean up and exit.
809 if (!FailingCommands.empty()) {
Reid Kleckner68eb60b2015-02-02 22:41:48 +0000810 if (!isSaveTempsEnabled())
Chad Rosierbe10f982011-08-02 17:58:04 +0000811 C.CleanupFileList(C.getTempFiles(), true);
812
813 Diag(clang::diag::note_drv_command_failed_diag_msg)
Douglas Katzmana67e50c2015-06-26 15:47:46 +0000814 << "Error generating preprocessed source(s).";
Justin Bognerbc89b182014-10-20 21:20:27 +0000815 return;
Chad Rosierbe10f982011-08-02 17:58:04 +0000816 }
Justin Bognerbc89b182014-10-20 21:20:27 +0000817
Justin Bognerc1fdf7f2014-10-20 21:47:56 +0000818 const ArgStringList &TempFiles = C.getTempFiles();
819 if (TempFiles.empty()) {
820 Diag(clang::diag::note_drv_command_failed_diag_msg)
Douglas Katzmana67e50c2015-06-26 15:47:46 +0000821 << "Error generating preprocessed source(s).";
Justin Bognerc1fdf7f2014-10-20 21:47:56 +0000822 return;
823 }
824
Justin Bognerbc89b182014-10-20 21:20:27 +0000825 Diag(clang::diag::note_drv_command_failed_diag_msg)
826 << "\n********************\n\n"
827 "PLEASE ATTACH THE FOLLOWING FILES TO THE BUG REPORT:\n"
828 "Preprocessed source(s) and associated run script(s) are located at:";
Justin Bognerbc89b182014-10-20 21:20:27 +0000829
Justin Bogner659ecc32014-10-20 22:47:23 +0000830 SmallString<128> VFS;
831 for (const char *TempFile : TempFiles) {
Justin Bognerc1fdf7f2014-10-20 21:47:56 +0000832 Diag(clang::diag::note_drv_command_failed_diag_msg) << TempFile;
Justin Bogner659ecc32014-10-20 22:47:23 +0000833 if (StringRef(TempFile).endswith(".cache")) {
834 // In some cases (modules) we'll dump extra data to help with reproducing
835 // the crash into a directory next to the output.
836 VFS = llvm::sys::path::filename(TempFile);
837 llvm::sys::path::append(VFS, "vfs", "vfs.yaml");
838 }
839 }
Justin Bognerc1fdf7f2014-10-20 21:47:56 +0000840
841 // Assume associated files are based off of the first temporary file.
Justin Bogner25645152014-10-21 17:24:44 +0000842 CrashReportInfo CrashInfo(TempFiles[0], VFS);
Justin Bognerc1fdf7f2014-10-20 21:47:56 +0000843
Justin Bogner25645152014-10-21 17:24:44 +0000844 std::string Script = CrashInfo.Filename.rsplit('.').first.str() + ".sh";
Justin Bognerc1fdf7f2014-10-20 21:47:56 +0000845 std::error_code EC;
Justin Bognerc1fdf7f2014-10-20 21:47:56 +0000846 llvm::raw_fd_ostream ScriptOS(Script, EC, llvm::sys::fs::F_Excl);
847 if (EC) {
848 Diag(clang::diag::note_drv_command_failed_diag_msg)
849 << "Error generating run script: " + Script + " " + EC.message();
850 } else {
Justin Bogner42220ed2015-03-12 00:14:35 +0000851 ScriptOS << "# Crash reproducer for " << getClangFullVersion() << "\n"
Justin Bognered9cbe02015-07-09 06:58:31 +0000852 << "# Driver args: ";
853 printArgList(ScriptOS, C.getInputArgs());
854 ScriptOS << "# Original command: ";
Justin Bogner42220ed2015-03-12 00:14:35 +0000855 Cmd.Print(ScriptOS, "\n", /*Quote=*/true);
Justin Bogner33bdbc62014-10-21 18:03:08 +0000856 Cmd.Print(ScriptOS, "\n", /*Quote=*/true, &CrashInfo);
Justin Bognerc1fdf7f2014-10-20 21:47:56 +0000857 Diag(clang::diag::note_drv_command_failed_diag_msg) << Script;
Justin Bognerbc89b182014-10-20 21:20:27 +0000858 }
Saleem Abdulrasool3661a822015-01-12 02:33:09 +0000859
860 for (const auto &A : C.getArgs().filtered(options::OPT_frewrite_map_file,
861 options::OPT_frewrite_map_file_EQ))
862 Diag(clang::diag::note_drv_command_failed_diag_msg) << A->getValue();
863
Justin Bognerbc89b182014-10-20 21:20:27 +0000864 Diag(clang::diag::note_drv_command_failed_diag_msg)
865 << "\n\n********************";
Chad Rosierbe10f982011-08-02 17:58:04 +0000866}
867
Justin Bogner0cd92482015-07-02 22:52:08 +0000868void Driver::setUpResponseFiles(Compilation &C, Command &Cmd) {
Oleg Ranevskyycd516372016-01-05 19:54:39 +0000869 // Since commandLineFitsWithinSystemLimits() may underestimate system's capacity
Reid Kleckner0290c9c2014-09-15 17:45:39 +0000870 // if the tool does not support response files, there is a chance/ that things
871 // will just work without a response file, so we silently just skip it.
Justin Bogner0cd92482015-07-02 22:52:08 +0000872 if (Cmd.getCreator().getResponseFilesSupport() == Tool::RF_None ||
Oleg Ranevskyycd516372016-01-05 19:54:39 +0000873 llvm::sys::commandLineFitsWithinSystemLimits(Cmd.getExecutable(), Cmd.getArguments()))
Reid Kleckner0290c9c2014-09-15 17:45:39 +0000874 return;
875
876 std::string TmpName = GetTemporaryPath("response", "txt");
Malcolm Parsonsf76f6502016-11-02 10:39:27 +0000877 Cmd.setResponseFile(C.addTempFile(C.getArgs().MakeArgString(TmpName)));
Reid Kleckner0290c9c2014-09-15 17:45:39 +0000878}
879
Douglas Katzmana67e50c2015-06-26 15:47:46 +0000880int Driver::ExecuteCompilation(
881 Compilation &C,
882 SmallVectorImpl<std::pair<int, const Command *>> &FailingCommands) {
Daniel Dunbar38bfda62009-07-01 20:03:04 +0000883 // Just print if -### was present.
884 if (C.getArgs().hasArg(options::OPT__HASH_HASH_HASH)) {
Hans Wennborgb212b342013-09-12 18:23:34 +0000885 C.getJobs().Print(llvm::errs(), "\n", true);
Daniel Dunbar38bfda62009-07-01 20:03:04 +0000886 return 0;
887 }
888
889 // If there were errors building the compilation, quit now.
Chad Rosierbe10f982011-08-02 17:58:04 +0000890 if (Diags.hasErrorOccurred())
Daniel Dunbar38bfda62009-07-01 20:03:04 +0000891 return 1;
892
Reid Kleckner0290c9c2014-09-15 17:45:39 +0000893 // Set up response file names for each command, if necessary
Justin Bogner0cd92482015-07-02 22:52:08 +0000894 for (auto &Job : C.getJobs())
895 setUpResponseFiles(C, Job);
Reid Kleckner0290c9c2014-09-15 17:45:39 +0000896
Justin Bogner0cd92482015-07-02 22:52:08 +0000897 C.ExecuteJobs(C.getJobs(), FailingCommands);
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +0000898
Daniel Dunbar38bfda62009-07-01 20:03:04 +0000899 // Remove temp files.
900 C.CleanupFileList(C.getTempFiles());
901
Daniel Dunbar07494792010-05-22 00:37:20 +0000902 // If the command succeeded, we are done.
Chad Rosierdd60e092013-01-29 20:15:05 +0000903 if (FailingCommands.empty())
904 return 0;
Daniel Dunbar07494792010-05-22 00:37:20 +0000905
Chad Rosierdd60e092013-01-29 20:15:05 +0000906 // Otherwise, remove result files and print extra information about abnormal
907 // failures.
Douglas Katzman6bbffc42015-06-25 18:51:37 +0000908 for (const auto &CmdPair : FailingCommands) {
909 int Res = CmdPair.first;
910 const Command *FailingCommand = CmdPair.second;
Daniel Dunbar38bfda62009-07-01 20:03:04 +0000911
Chad Rosierdd60e092013-01-29 20:15:05 +0000912 // Remove result files if we're not saving temps.
Reid Kleckner68eb60b2015-02-02 22:41:48 +0000913 if (!isSaveTempsEnabled()) {
Chad Rosierdd60e092013-01-29 20:15:05 +0000914 const JobAction *JA = cast<JobAction>(&FailingCommand->getSource());
915 C.CleanupFileMap(C.getResultFiles(), JA, true);
916
917 // Failure result files are valid unless we crashed.
918 if (Res < 0)
919 C.CleanupFileMap(C.getFailureResultFiles(), JA, true);
920 }
921
922 // Print extra information about abnormal failures, if possible.
923 //
924 // This is ad-hoc, but we don't want to be excessively noisy. If the result
Justin Bogner5aaf2e72014-06-26 20:59:36 +0000925 // status was 1, assume the command failed normally. In particular, if it
Chad Rosierdd60e092013-01-29 20:15:05 +0000926 // was the compiler then assume it gave a reasonable error code. Failures
927 // in other tools are less common, and they generally have worse
928 // diagnostics, so always print the diagnostic there.
929 const Tool &FailingTool = FailingCommand->getCreator();
930
931 if (!FailingCommand->getCreator().hasGoodDiagnostics() || Res != 1) {
932 // FIXME: See FIXME above regarding result code interpretation.
933 if (Res < 0)
934 Diag(clang::diag::err_drv_command_signalled)
Douglas Katzmana67e50c2015-06-26 15:47:46 +0000935 << FailingTool.getShortName();
Chad Rosierdd60e092013-01-29 20:15:05 +0000936 else
Douglas Katzmana67e50c2015-06-26 15:47:46 +0000937 Diag(clang::diag::err_drv_command_failed) << FailingTool.getShortName()
938 << Res;
Chad Rosierdd60e092013-01-29 20:15:05 +0000939 }
Peter Collingbourne119cfaa2011-11-21 00:01:05 +0000940 }
Chad Rosierdd60e092013-01-29 20:15:05 +0000941 return 0;
Daniel Dunbar38bfda62009-07-01 20:03:04 +0000942}
943
Daniel Dunbara7b5e212009-04-15 16:34:29 +0000944void Driver::PrintHelp(bool ShowHidden) const {
Hans Wennborg6ddc6902013-07-27 00:23:45 +0000945 unsigned IncludedFlagsBitmask;
946 unsigned ExcludedFlagsBitmask;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +0000947 std::tie(IncludedFlagsBitmask, ExcludedFlagsBitmask) =
Douglas Katzmana67e50c2015-06-26 15:47:46 +0000948 getIncludeExcludeOptionFlagMasks();
Hans Wennborg6ddc6902013-07-27 00:23:45 +0000949
950 ExcludedFlagsBitmask |= options::NoDriverOption;
951 if (!ShowHidden)
952 ExcludedFlagsBitmask |= HelpHidden;
953
954 getOpts().PrintHelp(llvm::outs(), Name.c_str(), DriverTitle.c_str(),
955 IncludedFlagsBitmask, ExcludedFlagsBitmask);
Daniel Dunbar7c925282009-03-31 21:38:17 +0000956}
957
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000958void Driver::PrintVersion(const Compilation &C, raw_ostream &OS) const {
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +0000959 // FIXME: The following handlers should use a callback mechanism, we don't
960 // know what the client would like to do.
Ted Kremenek4c0df3d2010-01-23 02:11:34 +0000961 OS << getClangFullVersion() << '\n';
Daniel Dunbarb10248802009-03-26 16:09:13 +0000962 const ToolChain &TC = C.getDefaultToolChain();
Daniel Dunbar08e41d62009-07-21 20:06:58 +0000963 OS << "Target: " << TC.getTripleString() << '\n';
Daniel Dunbar10978e42009-06-16 23:32:58 +0000964
965 // Print the threading model.
Jonathan Roelofsb140a102014-10-03 21:57:44 +0000966 if (Arg *A = C.getArgs().getLastArg(options::OPT_mthread_model)) {
967 // Don't print if the ToolChain would have barfed on it already
968 if (TC.isThreadModelSupported(A->getValue()))
969 OS << "Thread model: " << A->getValue();
970 } else
971 OS << "Thread model: " << TC.getThreadModel();
972 OS << '\n';
Chandler Carruth9ade6a92015-08-05 17:07:33 +0000973
974 // Print out the install directory.
975 OS << "InstalledDir: " << InstalledDir << '\n';
Daniel Dunbar5e0f6af2009-03-13 00:51:18 +0000976}
977
Chris Lattner86ed5b02010-05-05 05:53:24 +0000978/// PrintDiagnosticCategories - Implement the --print-diagnostic-categories
979/// option.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000980static void PrintDiagnosticCategories(raw_ostream &OS) {
Argyrios Kyrtzidis0e37afa2011-05-25 05:05:01 +0000981 // Skip the empty category.
Douglas Katzmana67e50c2015-06-26 15:47:46 +0000982 for (unsigned i = 1, max = DiagnosticIDs::getNumberOfCategories(); i != max;
983 ++i)
Argyrios Kyrtzidis0e37afa2011-05-25 05:05:01 +0000984 OS << i << ',' << DiagnosticIDs::getCategoryNameFromID(i) << '\n';
Chris Lattner86ed5b02010-05-05 05:53:24 +0000985}
986
Daniel Dunbarf0eddb82009-03-18 02:55:38 +0000987bool Driver::HandleImmediateArgs(const Compilation &C) {
Daniel Dunbar18974bd2010-06-11 22:00:19 +0000988 // The order these options are handled in gcc is all over the place, but we
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +0000989 // don't expect inconsistencies w.r.t. that to matter in practice.
Daniel Dunbar7c925282009-03-31 21:38:17 +0000990
Daniel Dunbar1b09e042010-09-17 02:47:28 +0000991 if (C.getArgs().hasArg(options::OPT_dumpmachine)) {
992 llvm::outs() << C.getDefaultToolChain().getTripleString() << '\n';
993 return false;
994 }
995
Daniel Dunbara9bbcfa2009-04-04 05:17:38 +0000996 if (C.getArgs().hasArg(options::OPT_dumpversion)) {
Daniel Dunbare26e5002011-01-12 00:43:47 +0000997 // Since -dumpversion is only implemented for pedantic GCC compatibility, we
998 // return an answer which matches our definition of __VERSION__.
999 //
1000 // If we want to return a more correct answer some day, then we should
1001 // introduce a non-pedantically GCC compatible mode to Clang in which we
1002 // provide sensible definitions for -dumpversion, __VERSION__, etc.
1003 llvm::outs() << "4.2.1\n";
Daniel Dunbara9bbcfa2009-04-04 05:17:38 +00001004 return false;
1005 }
Daniel Dunbarfb3d7472010-06-14 21:23:12 +00001006
Chris Lattner86ed5b02010-05-05 05:53:24 +00001007 if (C.getArgs().hasArg(options::OPT__print_diagnostic_categories)) {
1008 PrintDiagnosticCategories(llvm::outs());
1009 return false;
1010 }
Daniel Dunbara9bbcfa2009-04-04 05:17:38 +00001011
James Molloya3c85b82012-05-01 14:57:16 +00001012 if (C.getArgs().hasArg(options::OPT_help) ||
Daniel Dunbara7b5e212009-04-15 16:34:29 +00001013 C.getArgs().hasArg(options::OPT__help_hidden)) {
1014 PrintHelp(C.getArgs().hasArg(options::OPT__help_hidden));
Daniel Dunbar7c925282009-03-31 21:38:17 +00001015 return false;
1016 }
1017
Daniel Dunbarb0006ae2009-04-02 15:05:41 +00001018 if (C.getArgs().hasArg(options::OPT__version)) {
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001019 // Follow gcc behavior and use stdout for --version and stderr for -v.
Daniel Dunbar08e41d62009-07-21 20:06:58 +00001020 PrintVersion(C, llvm::outs());
Daniel Dunbarb0006ae2009-04-02 15:05:41 +00001021 return false;
1022 }
1023
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001024 if (C.getArgs().hasArg(options::OPT_v) ||
Daniel Dunbarf0eddb82009-03-18 02:55:38 +00001025 C.getArgs().hasArg(options::OPT__HASH_HASH_HASH)) {
Daniel Dunbar08e41d62009-07-21 20:06:58 +00001026 PrintVersion(C, llvm::errs());
Daniel Dunbar5e0f6af2009-03-13 00:51:18 +00001027 SuppressMissingInputWarning = true;
1028 }
1029
Daniel Dunbarf0eddb82009-03-18 02:55:38 +00001030 const ToolChain &TC = C.getDefaultToolChain();
Chandler Carruth0ae39aa2013-07-30 17:57:09 +00001031
1032 if (C.getArgs().hasArg(options::OPT_v))
1033 TC.printVerboseInfo(llvm::errs());
1034
Daniel Dunbard972e222009-03-20 04:37:21 +00001035 if (C.getArgs().hasArg(options::OPT_print_search_dirs)) {
1036 llvm::outs() << "programs: =";
Douglas Katzman51fe7bf2015-06-23 22:43:50 +00001037 bool separator = false;
1038 for (const std::string &Path : TC.getProgramPaths()) {
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001039 if (separator)
1040 llvm::outs() << ':';
Douglas Katzman51fe7bf2015-06-23 22:43:50 +00001041 llvm::outs() << Path;
1042 separator = true;
Daniel Dunbard972e222009-03-20 04:37:21 +00001043 }
1044 llvm::outs() << "\n";
Peter Collingbournefa9771f2011-09-06 02:08:31 +00001045 llvm::outs() << "libraries: =" << ResourceDir;
Joerg Sonnenberger9c3e69b2011-07-16 10:50:05 +00001046
Sebastian Pop980920a2012-04-16 04:16:43 +00001047 StringRef sysroot = C.getSysRoot();
Joerg Sonnenberger9c3e69b2011-07-16 10:50:05 +00001048
Douglas Katzman51fe7bf2015-06-23 22:43:50 +00001049 for (const std::string &Path : TC.getFilePaths()) {
1050 // Always print a separator. ResourceDir was the first item shown.
Peter Collingbournefa9771f2011-09-06 02:08:31 +00001051 llvm::outs() << ':';
Douglas Katzman51fe7bf2015-06-23 22:43:50 +00001052 // Interpretation of leading '=' is needed only for NetBSD.
1053 if (Path[0] == '=')
Douglas Katzman26eabf62015-06-24 15:10:30 +00001054 llvm::outs() << sysroot << Path.substr(1);
Joerg Sonnenberger9c3e69b2011-07-16 10:50:05 +00001055 else
Douglas Katzman51fe7bf2015-06-23 22:43:50 +00001056 llvm::outs() << Path;
Daniel Dunbard972e222009-03-20 04:37:21 +00001057 }
1058 llvm::outs() << "\n";
Daniel Dunbar7c925282009-03-31 21:38:17 +00001059 return false;
Daniel Dunbard972e222009-03-20 04:37:21 +00001060 }
1061
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001062 // FIXME: The following handlers should use a callback mechanism, we don't
1063 // know what the client would like to do.
Daniel Dunbarf0eddb82009-03-18 02:55:38 +00001064 if (Arg *A = C.getArgs().getLastArg(options::OPT_print_file_name_EQ)) {
Richard Smithbd55daf2012-11-01 04:30:05 +00001065 llvm::outs() << GetFilePath(A->getValue(), TC) << "\n";
Daniel Dunbar5e0f6af2009-03-13 00:51:18 +00001066 return false;
1067 }
1068
Daniel Dunbarf0eddb82009-03-18 02:55:38 +00001069 if (Arg *A = C.getArgs().getLastArg(options::OPT_print_prog_name_EQ)) {
Richard Smithbd55daf2012-11-01 04:30:05 +00001070 llvm::outs() << GetProgramPath(A->getValue(), TC) << "\n";
Daniel Dunbar5e0f6af2009-03-13 00:51:18 +00001071 return false;
1072 }
1073
Daniel Dunbarf0eddb82009-03-18 02:55:38 +00001074 if (C.getArgs().hasArg(options::OPT_print_libgcc_file_name)) {
Michal Gorny7cfe4802016-10-10 12:23:40 +00001075 ToolChain::RuntimeLibType RLT = TC.GetRuntimeLibType(C.getArgs());
1076 switch (RLT) {
1077 case ToolChain::RLT_CompilerRT:
1078 llvm::outs() << TC.getCompilerRT(C.getArgs(), "builtins") << "\n";
1079 break;
1080 case ToolChain::RLT_Libgcc:
1081 llvm::outs() << GetFilePath("libgcc.a", TC) << "\n";
1082 break;
1083 }
Daniel Dunbar5e0f6af2009-03-13 00:51:18 +00001084 return false;
1085 }
1086
Daniel Dunbar1b3ec3a2009-06-16 23:25:22 +00001087 if (C.getArgs().hasArg(options::OPT_print_multi_lib)) {
Douglas Katzmana34b7bf2015-06-30 19:32:57 +00001088 for (const Multilib &Multilib : TC.getMultilibs())
1089 llvm::outs() << Multilib << "\n";
Daniel Dunbar1b3ec3a2009-06-16 23:25:22 +00001090 return false;
1091 }
1092
Jonathan Roelofs2cea1be2014-02-12 03:21:20 +00001093 if (C.getArgs().hasArg(options::OPT_print_multi_directory)) {
Douglas Katzmana34b7bf2015-06-30 19:32:57 +00001094 for (const Multilib &Multilib : TC.getMultilibs()) {
Douglas Katzman6bbffc42015-06-25 18:51:37 +00001095 if (Multilib.gccSuffix().empty())
Jonathan Roelofs2cea1be2014-02-12 03:21:20 +00001096 llvm::outs() << ".\n";
1097 else {
Douglas Katzman6bbffc42015-06-25 18:51:37 +00001098 StringRef Suffix(Multilib.gccSuffix());
Jonathan Roelofs2cea1be2014-02-12 03:21:20 +00001099 assert(Suffix.front() == '/');
1100 llvm::outs() << Suffix.substr(1) << "\n";
1101 }
Jonathan Roelofs3fa96d82014-02-12 01:36:51 +00001102 }
Jonathan Roelofs0e7ec602014-02-12 01:29:25 +00001103 return false;
1104 }
Daniel Dunbar5e0f6af2009-03-13 00:51:18 +00001105 return true;
1106}
1107
Douglas Katzmanfd528672015-06-11 15:05:22 +00001108// Display an action graph human-readably. Action A is the "sink" node
1109// and latest-occuring action. Traversal is in pre-order, visiting the
1110// inputs to each action before printing the action itself.
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001111static unsigned PrintActions1(const Compilation &C, Action *A,
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001112 std::map<Action *, unsigned> &Ids) {
Douglas Katzmanfd528672015-06-11 15:05:22 +00001113 if (Ids.count(A)) // A was already visited.
Daniel Dunbaraaf1ea62009-03-13 12:19:02 +00001114 return Ids[A];
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001115
Daniel Dunbaraaf1ea62009-03-13 12:19:02 +00001116 std::string str;
1117 llvm::raw_string_ostream os(str);
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001118
Daniel Dunbaraaf1ea62009-03-13 12:19:02 +00001119 os << Action::getClassName(A->getKind()) << ", ";
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001120 if (InputAction *IA = dyn_cast<InputAction>(A)) {
Richard Smithbd55daf2012-11-01 04:30:05 +00001121 os << "\"" << IA->getInputArg().getValue() << "\"";
Daniel Dunbaraaf1ea62009-03-13 12:19:02 +00001122 } else if (BindArchAction *BIA = dyn_cast<BindArchAction>(A)) {
Douglas Katzmanb7e8ef02015-06-25 19:37:41 +00001123 os << '"' << BIA->getArchName() << '"' << ", {"
Nico Weber5a459f82016-02-23 19:30:43 +00001124 << PrintActions1(C, *BIA->input_begin(), Ids) << "}";
Samuel Antaod06239d2016-07-15 23:13:27 +00001125 } else if (OffloadAction *OA = dyn_cast<OffloadAction>(A)) {
1126 bool IsFirst = true;
1127 OA->doOnEachDependence(
1128 [&](Action *A, const ToolChain *TC, const char *BoundArch) {
1129 // E.g. for two CUDA device dependences whose bound arch is sm_20 and
1130 // sm_35 this will generate:
1131 // "cuda-device" (nvptx64-nvidia-cuda:sm_20) {#ID}, "cuda-device"
1132 // (nvptx64-nvidia-cuda:sm_35) {#ID}
1133 if (!IsFirst)
1134 os << ", ";
1135 os << '"';
1136 if (TC)
1137 os << A->getOffloadingKindPrefix();
1138 else
1139 os << "host";
1140 os << " (";
1141 os << TC->getTriple().normalize();
1142
1143 if (BoundArch)
1144 os << ":" << BoundArch;
1145 os << ")";
1146 os << '"';
1147 os << " {" << PrintActions1(C, A, Ids) << "}";
1148 IsFirst = false;
1149 });
Daniel Dunbaraaf1ea62009-03-13 12:19:02 +00001150 } else {
Samuel Antaod06239d2016-07-15 23:13:27 +00001151 const ActionList *AL = &A->getInputs();
Artem Belevich0ff05cd2015-07-13 23:27:56 +00001152
Artem Belevich23256752015-09-22 17:23:09 +00001153 if (AL->size()) {
1154 const char *Prefix = "{";
1155 for (Action *PreRequisite : *AL) {
1156 os << Prefix << PrintActions1(C, PreRequisite, Ids);
1157 Prefix = ", ";
1158 }
1159 os << "}";
1160 } else
1161 os << "{}";
Daniel Dunbaraaf1ea62009-03-13 12:19:02 +00001162 }
1163
Samuel Antaod06239d2016-07-15 23:13:27 +00001164 // Append offload info for all options other than the offloading action
1165 // itself (e.g. (cuda-device, sm_20) or (cuda-host)).
1166 std::string offload_str;
1167 llvm::raw_string_ostream offload_os(offload_str);
1168 if (!isa<OffloadAction>(A)) {
1169 auto S = A->getOffloadingKindPrefix();
1170 if (!S.empty()) {
1171 offload_os << ", (" << S;
1172 if (A->getOffloadingArch())
1173 offload_os << ", " << A->getOffloadingArch();
1174 offload_os << ")";
1175 }
1176 }
1177
Daniel Dunbaraaf1ea62009-03-13 12:19:02 +00001178 unsigned Id = Ids.size();
1179 Ids[A] = Id;
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001180 llvm::errs() << Id << ": " << os.str() << ", "
Samuel Antaod06239d2016-07-15 23:13:27 +00001181 << types::getTypeName(A->getType()) << offload_os.str() << "\n";
Daniel Dunbaraaf1ea62009-03-13 12:19:02 +00001182
1183 return Id;
1184}
1185
Douglas Katzmanfd528672015-06-11 15:05:22 +00001186// Print the action graphs in a compilation C.
1187// For example "clang -c file1.c file2.c" is composed of two subgraphs.
Daniel Dunbareb843be2009-03-18 03:13:20 +00001188void Driver::PrintActions(const Compilation &C) const {
Douglas Katzmanb7e8ef02015-06-25 19:37:41 +00001189 std::map<Action *, unsigned> Ids;
1190 for (Action *A : C.getActions())
1191 PrintActions1(C, A, Ids);
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00001192}
1193
Joerg Sonnenberger5fe4a7d2011-05-06 14:05:11 +00001194/// \brief Check whether the given input tree contains any compilation or
1195/// assembly actions.
1196static bool ContainsCompileOrAssembleAction(const Action *A) {
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001197 if (isa<CompileJobAction>(A) || isa<BackendJobAction>(A) ||
Bob Wilson23a55f12014-12-21 07:00:00 +00001198 isa<AssembleJobAction>(A))
Daniel Dunbar00d3d8e2010-06-29 16:38:33 +00001199 return true;
1200
Nico Weber5a459f82016-02-23 19:30:43 +00001201 for (const Action *Input : A->inputs())
Nico Weberfb80f962015-09-19 21:36:51 +00001202 if (ContainsCompileOrAssembleAction(Input))
Daniel Dunbar00d3d8e2010-06-29 16:38:33 +00001203 return true;
1204
1205 return false;
1206}
1207
Artem Belevich5e2a3ec2015-11-17 22:28:40 +00001208void Driver::BuildUniversalActions(Compilation &C, const ToolChain &TC,
1209 const InputList &BAInputs) const {
1210 DerivedArgList &Args = C.getArgs();
1211 ActionList &Actions = C.getActions();
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001212 llvm::PrettyStackTraceString CrashInfo("Building universal build actions");
1213 // Collect the list of architectures. Duplicates are allowed, but should only
1214 // be handled once (in the order seen).
Daniel Dunbare5dc4822009-03-13 20:33:35 +00001215 llvm::StringSet<> ArchNames;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001216 SmallVector<const char *, 4> Archs;
Saleem Abdulrasool688b6bc2014-12-29 19:01:36 +00001217 for (Arg *A : Args) {
Daniel Dunbar0bfb21e2009-11-19 03:26:40 +00001218 if (A->getOption().matches(options::OPT_arch)) {
Daniel Dunbar9c3f7c42009-09-08 23:37:30 +00001219 // Validate the option here; we don't save the type here because its
1220 // particular spelling may participate in other driver choices.
1221 llvm::Triple::ArchType Arch =
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001222 tools::darwin::getArchTypeForMachOArchName(A->getValue());
Daniel Dunbar9c3f7c42009-09-08 23:37:30 +00001223 if (Arch == llvm::Triple::UnknownArch) {
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001224 Diag(clang::diag::err_drv_invalid_arch_name) << A->getAsString(Args);
Daniel Dunbar9c3f7c42009-09-08 23:37:30 +00001225 continue;
1226 }
1227
Daniel Dunbar2da02722009-03-19 07:55:12 +00001228 A->claim();
David Blaikie61b86d42014-11-19 02:56:13 +00001229 if (ArchNames.insert(A->getValue()).second)
Richard Smithbd55daf2012-11-01 04:30:05 +00001230 Archs.push_back(A->getValue());
Daniel Dunbarf479c122009-03-12 18:40:18 +00001231 }
1232 }
1233
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001234 // When there is no explicit arch for this platform, make sure we still bind
1235 // the architecture (to the default) so that -Xarch_ is handled correctly.
Daniel Dunbareb843be2009-03-18 03:13:20 +00001236 if (!Archs.size())
Daniel Dunbarc3bd9f52012-11-08 03:38:26 +00001237 Archs.push_back(Args.MakeArgString(TC.getDefaultUniversalArchName()));
Daniel Dunbarf479c122009-03-12 18:40:18 +00001238
Daniel Dunbarf479c122009-03-12 18:40:18 +00001239 ActionList SingleActions;
Justin Lebar0f3474c2016-02-11 02:00:50 +00001240 BuildActions(C, Args, BAInputs, SingleActions);
Daniel Dunbarf479c122009-03-12 18:40:18 +00001241
Daniel Dunbar6beaf512010-06-04 18:28:41 +00001242 // Add in arch bindings for every top level action, as well as lipo and
1243 // dsymutil steps if needed.
Nico Weberfb80f962015-09-19 21:36:51 +00001244 for (Action* Act : SingleActions) {
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001245 // Make sure we can lipo this kind of output. If not (and it is an actual
1246 // output) then we disallow, since we can't create an output file with the
1247 // right name without overwriting it. We could remove this oddity by just
1248 // changing the output names to include the arch, which would also fix
Daniel Dunbarf479c122009-03-12 18:40:18 +00001249 // -save-temps. Compatibility wins for now.
1250
Daniel Dunbare2ca3bd2009-03-13 17:46:02 +00001251 if (Archs.size() > 1 && !types::canLipoType(Act->getType()))
Daniel Dunbarf479c122009-03-12 18:40:18 +00001252 Diag(clang::diag::err_drv_invalid_output_with_multiple_archs)
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001253 << types::getTypeName(Act->getType());
Daniel Dunbarf479c122009-03-12 18:40:18 +00001254
1255 ActionList Inputs;
Justin Lebar41094612016-01-11 23:07:27 +00001256 for (unsigned i = 0, e = Archs.size(); i != e; ++i)
1257 Inputs.push_back(C.MakeAction<BindArchAction>(Act, Archs[i]));
Daniel Dunbarf479c122009-03-12 18:40:18 +00001258
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001259 // Lipo if necessary, we do it this way because we need to set the arch flag
1260 // so that -Xarch_ gets overwritten.
Daniel Dunbarf479c122009-03-12 18:40:18 +00001261 if (Inputs.size() == 1 || Act->getType() == types::TY_Nothing)
1262 Actions.append(Inputs.begin(), Inputs.end());
1263 else
Justin Lebar41094612016-01-11 23:07:27 +00001264 Actions.push_back(C.MakeAction<LipoJobAction>(Inputs, Act->getType()));
Daniel Dunbar6beaf512010-06-04 18:28:41 +00001265
Eric Christopher65c05fa2012-02-06 19:43:51 +00001266 // Handle debug info queries.
1267 Arg *A = Args.getLastArg(options::OPT_g_Group);
David Blaikie6f9f4eb2012-04-15 21:22:10 +00001268 if (A && !A->getOption().matches(options::OPT_g0) &&
1269 !A->getOption().matches(options::OPT_gstabs) &&
1270 ContainsCompileOrAssembleAction(Actions.back())) {
Chad Rosier62135492012-07-09 17:31:28 +00001271
David Blaikie6f9f4eb2012-04-15 21:22:10 +00001272 // Add a 'dsymutil' step if necessary, when debug info is enabled and we
1273 // have a compile input. We need to run 'dsymutil' ourselves in such cases
Eric Christopher776c26f2013-01-28 17:39:03 +00001274 // because the debug info will refer to a temporary object file which
David Blaikie6f9f4eb2012-04-15 21:22:10 +00001275 // will be removed at the end of the compilation process.
1276 if (Act->getType() == types::TY_Image) {
1277 ActionList Inputs;
1278 Inputs.push_back(Actions.back());
1279 Actions.pop_back();
Justin Lebar41094612016-01-11 23:07:27 +00001280 Actions.push_back(
1281 C.MakeAction<DsymutilJobAction>(Inputs, types::TY_dSYM));
Daniel Dunbar6beaf512010-06-04 18:28:41 +00001282 }
David Blaikie6f9f4eb2012-04-15 21:22:10 +00001283
Ben Langmuir9b9a8d32014-02-06 18:53:25 +00001284 // Verify the debug info output.
Alp Tokere9d2bfc2014-01-17 02:06:23 +00001285 if (Args.hasArg(options::OPT_verify_debug_info)) {
Justin Lebar41094612016-01-11 23:07:27 +00001286 Action* LastAction = Actions.back();
David Blaikie6f9f4eb2012-04-15 21:22:10 +00001287 Actions.pop_back();
Justin Lebar41094612016-01-11 23:07:27 +00001288 Actions.push_back(C.MakeAction<VerifyDebugInfoJobAction>(
1289 LastAction, types::TY_Nothing));
David Blaikie6f9f4eb2012-04-15 21:22:10 +00001290 }
1291 }
Daniel Dunbarf479c122009-03-12 18:40:18 +00001292 }
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00001293}
1294
Hans Wennborg6ee64d52013-08-06 00:20:31 +00001295/// \brief Check that the file referenced by Value exists. If it doesn't,
1296/// issue a diagnostic and return false.
Alp Toker8c8a8752013-12-03 06:53:35 +00001297static bool DiagnoseInputExistence(const Driver &D, const DerivedArgList &Args,
Hans Wennborg12f4f8b2016-04-15 01:12:32 +00001298 StringRef Value, types::ID Ty) {
Hans Wennborg6ee64d52013-08-06 00:20:31 +00001299 if (!D.getCheckInputsExist())
1300 return true;
1301
1302 // stdin always exists.
1303 if (Value == "-")
1304 return true;
1305
1306 SmallString<64> Path(Value);
1307 if (Arg *WorkDir = Args.getLastArg(options::OPT_working_directory)) {
Yaron Keren92e1b622015-03-18 10:17:07 +00001308 if (!llvm::sys::path::is_absolute(Path)) {
Hans Wennborg6ee64d52013-08-06 00:20:31 +00001309 SmallString<64> Directory(WorkDir->getValue());
1310 llvm::sys::path::append(Directory, Value);
1311 Path.assign(Directory);
1312 }
1313 }
1314
1315 if (llvm::sys::fs::exists(Twine(Path)))
1316 return true;
1317
Hans Wennborg12f4f8b2016-04-15 01:12:32 +00001318 if (D.IsCLMode()) {
1319 if (!llvm::sys::path::is_absolute(Twine(Path)) &&
1320 llvm::sys::Process::FindInEnvPath("LIB", Value))
1321 return true;
1322
1323 if (Args.hasArg(options::OPT__SLASH_link) && Ty == types::TY_Object) {
1324 // Arguments to the /link flag might cause the linker to search for object
1325 // and library files in paths we don't know about. Don't error in such
1326 // cases.
1327 return true;
1328 }
1329 }
Hans Wennborg23d26a32014-06-18 17:21:50 +00001330
Yaron Keren92e1b622015-03-18 10:17:07 +00001331 D.Diag(clang::diag::err_drv_no_such_file) << Path;
Hans Wennborg6ee64d52013-08-06 00:20:31 +00001332 return false;
1333}
1334
Chad Rosierecdede82011-08-12 22:08:57 +00001335// Construct a the list of inputs and their types.
Hans Wennborg55362852014-05-02 22:55:30 +00001336void Driver::BuildInputs(const ToolChain &TC, DerivedArgList &Args,
Chad Rosierecdede82011-08-12 22:08:57 +00001337 InputList &Inputs) const {
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001338 // Track the current user specified (-x) input. We also explicitly track the
1339 // argument used to set the type; we only want to claim the type when we
1340 // actually use it, so we warn about unused -x arguments.
Daniel Dunbarc5a5ac52009-03-13 17:57:10 +00001341 types::ID InputType = types::TY_Nothing;
Craig Topper92fc2df2014-05-17 16:56:41 +00001342 Arg *InputTypeArg = nullptr;
Daniel Dunbarc5a5ac52009-03-13 17:57:10 +00001343
Hans Wennborg0d0b19c2013-08-12 18:34:17 +00001344 // The last /TC or /TP option sets the input type to C or C++ globally.
Ehsan Akhgaric249abb2014-09-12 21:44:24 +00001345 if (Arg *TCTP = Args.getLastArgNoClaim(options::OPT__SLASH_TC,
1346 options::OPT__SLASH_TP)) {
Hans Wennborg6ee64d52013-08-06 00:20:31 +00001347 InputTypeArg = TCTP;
Hans Wennborg0d0b19c2013-08-12 18:34:17 +00001348 InputType = TCTP->getOption().matches(options::OPT__SLASH_TC)
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001349 ? types::TY_C
1350 : types::TY_CXX;
Hans Wennborg6ee64d52013-08-06 00:20:31 +00001351
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001352 arg_iterator it =
1353 Args.filtered_begin(options::OPT__SLASH_TC, options::OPT__SLASH_TP);
Hans Wennborg0d0b19c2013-08-12 18:34:17 +00001354 const arg_iterator ie = Args.filtered_end();
1355 Arg *Previous = *it++;
1356 bool ShowNote = false;
1357 while (it != ie) {
Hans Wennborgd9ad0682013-09-11 16:38:41 +00001358 Diag(clang::diag::warn_drv_overriding_flag_option)
1359 << Previous->getSpelling() << (*it)->getSpelling();
Hans Wennborg0d0b19c2013-08-12 18:34:17 +00001360 Previous = *it++;
1361 ShowNote = true;
Hans Wennborg6ee64d52013-08-06 00:20:31 +00001362 }
Hans Wennborg0d0b19c2013-08-12 18:34:17 +00001363 if (ShowNote)
1364 Diag(clang::diag::note_drv_t_option_is_global);
Hans Wennborg6ee64d52013-08-06 00:20:31 +00001365
1366 // No driver mode exposes -x and /TC or /TP; we don't support mixing them.
1367 assert(!Args.hasArg(options::OPT_x) && "-x and /TC or /TP is not allowed");
1368 }
1369
Saleem Abdulrasool688b6bc2014-12-29 19:01:36 +00001370 for (Arg *A : Args) {
Michael J. Spencerad3ccc32012-08-20 21:41:17 +00001371 if (A->getOption().getKind() == Option::InputClass) {
Richard Smithbd55daf2012-11-01 04:30:05 +00001372 const char *Value = A->getValue();
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00001373 types::ID Ty = types::TY_INVALID;
1374
1375 // Infer the input type if necessary.
Daniel Dunbarc5a5ac52009-03-13 17:57:10 +00001376 if (InputType == types::TY_Nothing) {
1377 // If there was an explicit arg for this, claim it.
1378 if (InputTypeArg)
1379 InputTypeArg->claim();
1380
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00001381 // stdin must be handled specially.
1382 if (memcmp(Value, "-", 2) == 0) {
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001383 // If running with -E, treat as a C input (this changes the builtin
1384 // macros, for example). This may be overridden by -ObjC below.
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00001385 //
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001386 // Otherwise emit an error but still use a valid type to avoid
1387 // spurious errors (e.g., no inputs).
Hans Wennborg70850d82013-07-18 20:29:38 +00001388 if (!Args.hasArgNoClaim(options::OPT_E) && !CCCIsCPP())
Hans Wennborgcfdd8b52014-01-29 01:04:40 +00001389 Diag(IsCLMode() ? clang::diag::err_drv_unknown_stdin_type_clang_cl
1390 : clang::diag::err_drv_unknown_stdin_type);
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00001391 Ty = types::TY_C;
1392 } else {
Joerg Sonnenbergerbdbdf702011-03-16 22:45:02 +00001393 // Otherwise lookup by extension.
1394 // Fallback is C if invoked as C preprocessor or Object otherwise.
1395 // We use a host hook here because Darwin at least has its own
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001396 // idea of what .s is.
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00001397 if (const char *Ext = strrchr(Value, '.'))
Daniel Dunbarcc7df6c2010-08-02 05:43:56 +00001398 Ty = TC.LookupTypeForExtension(Ext + 1);
Daniel Dunbarea9f0322009-03-20 23:39:23 +00001399
Joerg Sonnenbergerbdbdf702011-03-16 22:45:02 +00001400 if (Ty == types::TY_INVALID) {
Hans Wennborg70850d82013-07-18 20:29:38 +00001401 if (CCCIsCPP())
Joerg Sonnenbergerbdbdf702011-03-16 22:45:02 +00001402 Ty = types::TY_C;
1403 else
1404 Ty = types::TY_Object;
1405 }
Daniel Dunbar0ac94452010-02-17 20:32:58 +00001406
1407 // If the driver is invoked as C++ compiler (like clang++ or c++) it
1408 // should autodetect some input files as C++ for g++ compatibility.
Hans Wennborg70850d82013-07-18 20:29:38 +00001409 if (CCCIsCXX()) {
Daniel Dunbar0ac94452010-02-17 20:32:58 +00001410 types::ID OldTy = Ty;
1411 Ty = types::lookupCXXTypeForCType(Ty);
1412
1413 if (Ty != OldTy)
1414 Diag(clang::diag::warn_drv_treating_input_as_cxx)
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001415 << getTypeName(OldTy) << getTypeName(Ty);
Daniel Dunbar0ac94452010-02-17 20:32:58 +00001416 }
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00001417 }
1418
Daniel Dunbar82b22102009-05-18 21:47:54 +00001419 // -ObjC and -ObjC++ override the default language, but only for "source
1420 // files". We just treat everything that isn't a linker input as a
1421 // source file.
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001422 //
Daniel Dunbar82b22102009-05-18 21:47:54 +00001423 // FIXME: Clean this up if we move the phase sequence into the type.
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00001424 if (Ty != types::TY_Object) {
1425 if (Args.hasArg(options::OPT_ObjC))
1426 Ty = types::TY_ObjC;
1427 else if (Args.hasArg(options::OPT_ObjCXX))
1428 Ty = types::TY_ObjCXX;
1429 }
1430 } else {
1431 assert(InputTypeArg && "InputType set w/o InputTypeArg");
Ehsan Akhgari7e954ea2014-09-12 18:15:10 +00001432 if (!InputTypeArg->getOption().matches(options::OPT_x)) {
1433 // If emulating cl.exe, make sure that /TC and /TP don't affect input
1434 // object files.
1435 const char *Ext = strrchr(Value, '.');
1436 if (Ext && TC.LookupTypeForExtension(Ext + 1) == types::TY_Object)
1437 Ty = types::TY_Object;
1438 }
1439 if (Ty == types::TY_INVALID) {
1440 Ty = InputType;
1441 InputTypeArg->claim();
1442 }
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00001443 }
1444
Hans Wennborg12f4f8b2016-04-15 01:12:32 +00001445 if (DiagnoseInputExistence(*this, Args, Value, Ty))
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00001446 Inputs.push_back(std::make_pair(Ty, A));
1447
Hans Wennborg6ee64d52013-08-06 00:20:31 +00001448 } else if (A->getOption().matches(options::OPT__SLASH_Tc)) {
1449 StringRef Value = A->getValue();
Hans Wennborg12f4f8b2016-04-15 01:12:32 +00001450 if (DiagnoseInputExistence(*this, Args, Value, types::TY_C)) {
Hans Wennborg6ee64d52013-08-06 00:20:31 +00001451 Arg *InputArg = MakeInputArg(Args, Opts, A->getValue());
1452 Inputs.push_back(std::make_pair(types::TY_C, InputArg));
1453 }
1454 A->claim();
1455 } else if (A->getOption().matches(options::OPT__SLASH_Tp)) {
1456 StringRef Value = A->getValue();
Hans Wennborg12f4f8b2016-04-15 01:12:32 +00001457 if (DiagnoseInputExistence(*this, Args, Value, types::TY_CXX)) {
Hans Wennborg6ee64d52013-08-06 00:20:31 +00001458 Arg *InputArg = MakeInputArg(Args, Opts, A->getValue());
1459 Inputs.push_back(std::make_pair(types::TY_CXX, InputArg));
1460 }
1461 A->claim();
Michael J. Spencer66e2b202012-10-19 22:37:06 +00001462 } else if (A->getOption().hasFlag(options::LinkerInput)) {
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001463 // Just treat as object type, we could make a special type for this if
1464 // necessary.
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00001465 Inputs.push_back(std::make_pair(types::TY_Object, A));
1466
Daniel Dunbar0bfb21e2009-11-19 03:26:40 +00001467 } else if (A->getOption().matches(options::OPT_x)) {
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001468 InputTypeArg = A;
Richard Smithbd55daf2012-11-01 04:30:05 +00001469 InputType = types::lookupTypeForTypeSpecifier(A->getValue());
Chad Rosier706c2352012-04-07 00:01:31 +00001470 A->claim();
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00001471
1472 // Follow gcc behavior and treat as linker input for invalid -x
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001473 // options. Its not clear why we shouldn't just revert to unknown; but
Michael J. Spencer1a4fe8c2010-12-17 21:22:33 +00001474 // this isn't very important, we might as well be bug compatible.
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00001475 if (!InputType) {
Richard Smithbd55daf2012-11-01 04:30:05 +00001476 Diag(clang::diag::err_drv_unknown_language) << A->getValue();
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00001477 InputType = types::TY_Object;
1478 }
1479 }
1480 }
Hans Wennborg70850d82013-07-18 20:29:38 +00001481 if (CCCIsCPP() && Inputs.empty()) {
Joerg Sonnenbergerb86f5f42011-03-06 23:31:01 +00001482 // If called as standalone preprocessor, stdin is processed
1483 // if no other input is present.
Hans Wennborg6ee64d52013-08-06 00:20:31 +00001484 Arg *A = MakeInputArg(Args, Opts, "-");
Joerg Sonnenbergerb86f5f42011-03-06 23:31:01 +00001485 Inputs.push_back(std::make_pair(types::TY_C, A));
1486 }
Chad Rosierecdede82011-08-12 22:08:57 +00001487}
1488
Samuel Antao64e965e2016-09-30 15:34:19 +00001489namespace {
1490/// Provides a convenient interface for different programming models to generate
1491/// the required device actions.
1492class OffloadingActionBuilder final {
1493 /// Flag used to trace errors in the builder.
1494 bool IsValid = false;
1495
1496 /// The compilation that is using this builder.
1497 Compilation &C;
1498
Samuel Antao64e965e2016-09-30 15:34:19 +00001499 /// Map between an input argument and the offload kinds used to process it.
1500 std::map<const Arg *, unsigned> InputArgToOffloadKindMap;
1501
1502 /// Builder interface. It doesn't build anything or keep any state.
1503 class DeviceActionBuilder {
1504 public:
1505 typedef llvm::SmallVector<phases::ID, phases::MaxNumberOfPhases> PhasesTy;
1506
1507 enum ActionBuilderReturnCode {
1508 // The builder acted successfully on the current action.
1509 ABRT_Success,
1510 // The builder didn't have to act on the current action.
1511 ABRT_Inactive,
1512 // The builder was successful and requested the host action to not be
1513 // generated.
1514 ABRT_Ignore_Host,
1515 };
1516
1517 protected:
1518 /// Compilation associated with this builder.
1519 Compilation &C;
1520
1521 /// Tool chains associated with this builder. The same programming
1522 /// model may have associated one or more tool chains.
1523 SmallVector<const ToolChain *, 2> ToolChains;
1524
1525 /// The derived arguments associated with this builder.
1526 DerivedArgList &Args;
1527
1528 /// The inputs associated with this builder.
1529 const Driver::InputList &Inputs;
1530
1531 /// The associated offload kind.
1532 Action::OffloadKind AssociatedOffloadKind = Action::OFK_None;
1533
1534 public:
1535 DeviceActionBuilder(Compilation &C, DerivedArgList &Args,
1536 const Driver::InputList &Inputs,
1537 Action::OffloadKind AssociatedOffloadKind)
1538 : C(C), Args(Args), Inputs(Inputs),
1539 AssociatedOffloadKind(AssociatedOffloadKind) {}
1540 virtual ~DeviceActionBuilder() {}
1541
1542 /// Fill up the array \a DA with all the device dependences that should be
1543 /// added to the provided host action \a HostAction. By default it is
1544 /// inactive.
1545 virtual ActionBuilderReturnCode
Samuel Antao28c4f182016-10-27 17:08:03 +00001546 getDeviceDependences(OffloadAction::DeviceDependences &DA,
1547 phases::ID CurPhase, phases::ID FinalPhase,
1548 PhasesTy &Phases) {
Samuel Antao64e965e2016-09-30 15:34:19 +00001549 return ABRT_Inactive;
1550 }
1551
1552 /// Update the state to include the provided host action \a HostAction as a
1553 /// dependency of the current device action. By default it is inactive.
1554 virtual ActionBuilderReturnCode addDeviceDepences(Action *HostAction) {
1555 return ABRT_Inactive;
1556 }
1557
1558 /// Append top level actions generated by the builder. Return true if errors
1559 /// were found.
1560 virtual void appendTopLevelActions(ActionList &AL) {}
1561
1562 /// Append linker actions generated by the builder. Return true if errors
1563 /// were found.
1564 virtual void appendLinkDependences(OffloadAction::DeviceDependences &DA) {}
1565
1566 /// Initialize the builder. Return true if any initialization errors are
1567 /// found.
1568 virtual bool initialize() { return false; }
1569
Samuel Antao69d6f312016-10-27 17:50:43 +00001570 /// Return true if the builder can use bundling/unbundling.
1571 virtual bool canUseBundlerUnbundler() const { return false; }
1572
Samuel Antao64e965e2016-09-30 15:34:19 +00001573 /// Return true if this builder is valid. We have a valid builder if we have
1574 /// associated device tool chains.
1575 bool isValid() { return !ToolChains.empty(); }
1576
1577 /// Return the associated offload kind.
1578 Action::OffloadKind getAssociatedOffloadKind() {
1579 return AssociatedOffloadKind;
1580 }
1581 };
1582
1583 /// \brief CUDA action builder. It injects device code in the host backend
1584 /// action.
1585 class CudaActionBuilder final : public DeviceActionBuilder {
1586 /// Flags to signal if the user requested host-only or device-only
1587 /// compilation.
1588 bool CompileHostOnly = false;
1589 bool CompileDeviceOnly = false;
1590
1591 /// List of GPU architectures to use in this compilation.
1592 SmallVector<CudaArch, 4> GpuArchList;
1593
1594 /// The CUDA actions for the current input.
1595 ActionList CudaDeviceActions;
1596
1597 /// The CUDA fat binary if it was generated for the current input.
1598 Action *CudaFatBinary = nullptr;
1599
1600 /// Flag that is set to true if this builder acted on the current input.
1601 bool IsActive = false;
1602
1603 public:
1604 CudaActionBuilder(Compilation &C, DerivedArgList &Args,
1605 const Driver::InputList &Inputs)
1606 : DeviceActionBuilder(C, Args, Inputs, Action::OFK_Cuda) {}
1607
1608 ActionBuilderReturnCode
Samuel Antao28c4f182016-10-27 17:08:03 +00001609 getDeviceDependences(OffloadAction::DeviceDependences &DA,
1610 phases::ID CurPhase, phases::ID FinalPhase,
1611 PhasesTy &Phases) override {
Samuel Antao64e965e2016-09-30 15:34:19 +00001612 if (!IsActive)
1613 return ABRT_Inactive;
1614
1615 // If we don't have more CUDA actions, we don't have any dependences to
1616 // create for the host.
1617 if (CudaDeviceActions.empty())
1618 return ABRT_Success;
1619
1620 assert(CudaDeviceActions.size() == GpuArchList.size() &&
1621 "Expecting one action per GPU architecture.");
1622 assert(!CompileHostOnly &&
1623 "Not expecting CUDA actions in host-only compilation.");
1624
1625 // If we are generating code for the device or we are in a backend phase,
1626 // we attempt to generate the fat binary. We compile each arch to ptx and
1627 // assemble to cubin, then feed the cubin *and* the ptx into a device
1628 // "link" action, which uses fatbinary to combine these cubins into one
1629 // fatbin. The fatbin is then an input to the host action if not in
1630 // device-only mode.
1631 if (CompileDeviceOnly || CurPhase == phases::Backend) {
1632 ActionList DeviceActions;
1633 for (unsigned I = 0, E = GpuArchList.size(); I != E; ++I) {
1634 // Produce the device action from the current phase up to the assemble
1635 // phase.
1636 for (auto Ph : Phases) {
1637 // Skip the phases that were already dealt with.
1638 if (Ph < CurPhase)
1639 continue;
1640 // We have to be consistent with the host final phase.
1641 if (Ph > FinalPhase)
1642 break;
1643
1644 CudaDeviceActions[I] = C.getDriver().ConstructPhaseAction(
1645 C, Args, Ph, CudaDeviceActions[I]);
1646
1647 if (Ph == phases::Assemble)
1648 break;
1649 }
1650
1651 // If we didn't reach the assemble phase, we can't generate the fat
1652 // binary. We don't need to generate the fat binary if we are not in
1653 // device-only mode.
1654 if (!isa<AssembleJobAction>(CudaDeviceActions[I]) ||
1655 CompileDeviceOnly)
1656 continue;
1657
1658 Action *AssembleAction = CudaDeviceActions[I];
1659 assert(AssembleAction->getType() == types::TY_Object);
1660 assert(AssembleAction->getInputs().size() == 1);
1661
1662 Action *BackendAction = AssembleAction->getInputs()[0];
1663 assert(BackendAction->getType() == types::TY_PP_Asm);
1664
1665 for (auto &A : {AssembleAction, BackendAction}) {
1666 OffloadAction::DeviceDependences DDep;
1667 DDep.add(*A, *ToolChains.front(), CudaArchToString(GpuArchList[I]),
1668 Action::OFK_Cuda);
1669 DeviceActions.push_back(
1670 C.MakeAction<OffloadAction>(DDep, A->getType()));
1671 }
1672 }
1673
1674 // We generate the fat binary if we have device input actions.
1675 if (!DeviceActions.empty()) {
1676 CudaFatBinary =
1677 C.MakeAction<LinkJobAction>(DeviceActions, types::TY_CUDA_FATBIN);
1678
1679 if (!CompileDeviceOnly) {
1680 DA.add(*CudaFatBinary, *ToolChains.front(), /*BoundArch=*/nullptr,
1681 Action::OFK_Cuda);
1682 // Clear the fat binary, it is already a dependence to an host
1683 // action.
1684 CudaFatBinary = nullptr;
1685 }
1686
1687 // Remove the CUDA actions as they are already connected to an host
1688 // action or fat binary.
1689 CudaDeviceActions.clear();
1690 }
1691
1692 // We avoid creating host action in device-only mode.
1693 return CompileDeviceOnly ? ABRT_Ignore_Host : ABRT_Success;
Samuel Antao5b1a89a2016-10-27 00:53:34 +00001694 } else if (CurPhase > phases::Backend) {
1695 // If we are past the backend phase and still have a device action, we
1696 // don't have to do anything as this action is already a device
1697 // top-level action.
1698 return ABRT_Success;
Samuel Antao64e965e2016-09-30 15:34:19 +00001699 }
1700
1701 assert(CurPhase < phases::Backend && "Generating single CUDA "
1702 "instructions should only occur "
1703 "before the backend phase!");
1704
1705 // By default, we produce an action for each device arch.
1706 for (Action *&A : CudaDeviceActions)
1707 A = C.getDriver().ConstructPhaseAction(C, Args, CurPhase, A);
1708
1709 return ABRT_Success;
1710 }
1711
1712 ActionBuilderReturnCode addDeviceDepences(Action *HostAction) override {
1713 // While generating code for CUDA, we only depend on the host input action
1714 // to trigger the creation of all the CUDA device actions.
1715
1716 // If we are dealing with an input action, replicate it for each GPU
1717 // architecture. If we are in host-only mode we return 'success' so that
1718 // the host uses the CUDA offload kind.
1719 if (auto *IA = dyn_cast<InputAction>(HostAction)) {
1720 assert(!GpuArchList.empty() &&
1721 "We should have at least one GPU architecture.");
1722
1723 // If the host input is not CUDA, we don't need to bother about this
1724 // input.
1725 if (IA->getType() != types::TY_CUDA) {
1726 // The builder will ignore this input.
1727 IsActive = false;
1728 return ABRT_Inactive;
1729 }
1730
1731 // Set the flag to true, so that the builder acts on the current input.
1732 IsActive = true;
1733
1734 if (CompileHostOnly)
1735 return ABRT_Success;
1736
1737 // Replicate inputs for each GPU architecture.
1738 for (unsigned I = 0, E = GpuArchList.size(); I != E; ++I)
1739 CudaDeviceActions.push_back(C.MakeAction<InputAction>(
1740 IA->getInputArg(), types::TY_CUDA_DEVICE));
1741
1742 return ABRT_Success;
1743 }
1744
1745 return IsActive ? ABRT_Success : ABRT_Inactive;
1746 }
1747
1748 void appendTopLevelActions(ActionList &AL) override {
1749 // Utility to append actions to the top level list.
1750 auto AddTopLevel = [&](Action *A, CudaArch BoundArch) {
1751 OffloadAction::DeviceDependences Dep;
1752 Dep.add(*A, *ToolChains.front(), CudaArchToString(BoundArch),
1753 Action::OFK_Cuda);
1754 AL.push_back(C.MakeAction<OffloadAction>(Dep, A->getType()));
1755 };
1756
1757 // If we have a fat binary, add it to the list.
1758 if (CudaFatBinary) {
1759 AddTopLevel(CudaFatBinary, CudaArch::UNKNOWN);
1760 CudaDeviceActions.clear();
1761 CudaFatBinary = nullptr;
1762 return;
1763 }
1764
1765 if (CudaDeviceActions.empty())
1766 return;
1767
1768 // If we have CUDA actions at this point, that's because we have a have
1769 // partial compilation, so we should have an action for each GPU
1770 // architecture.
1771 assert(CudaDeviceActions.size() == GpuArchList.size() &&
1772 "Expecting one action per GPU architecture.");
1773 assert(ToolChains.size() == 1 &&
1774 "Expecting to have a sing CUDA toolchain.");
1775 for (unsigned I = 0, E = GpuArchList.size(); I != E; ++I)
1776 AddTopLevel(CudaDeviceActions[I], GpuArchList[I]);
1777
1778 CudaDeviceActions.clear();
1779 }
1780
1781 bool initialize() override {
1782 // We don't need to support CUDA.
1783 if (!C.hasOffloadToolChain<Action::OFK_Cuda>())
1784 return false;
1785
1786 const ToolChain *HostTC = C.getSingleOffloadToolChain<Action::OFK_Host>();
1787 assert(HostTC && "No toolchain for host compilation.");
1788 if (HostTC->getTriple().isNVPTX()) {
1789 // We do not support targeting NVPTX for host compilation. Throw
1790 // an error and abort pipeline construction early so we don't trip
1791 // asserts that assume device-side compilation.
1792 C.getDriver().Diag(diag::err_drv_cuda_nvptx_host);
1793 return true;
1794 }
1795
1796 ToolChains.push_back(C.getSingleOffloadToolChain<Action::OFK_Cuda>());
1797
1798 Arg *PartialCompilationArg = Args.getLastArg(
1799 options::OPT_cuda_host_only, options::OPT_cuda_device_only,
1800 options::OPT_cuda_compile_host_device);
1801 CompileHostOnly = PartialCompilationArg &&
1802 PartialCompilationArg->getOption().matches(
1803 options::OPT_cuda_host_only);
1804 CompileDeviceOnly = PartialCompilationArg &&
1805 PartialCompilationArg->getOption().matches(
1806 options::OPT_cuda_device_only);
1807
1808 // Collect all cuda_gpu_arch parameters, removing duplicates.
1809 llvm::SmallSet<CudaArch, 4> GpuArchs;
1810 bool Error = false;
1811 for (Arg *A : Args) {
1812 if (!A->getOption().matches(options::OPT_cuda_gpu_arch_EQ))
1813 continue;
1814 A->claim();
1815
1816 const auto &ArchStr = A->getValue();
1817 CudaArch Arch = StringToCudaArch(ArchStr);
1818 if (Arch == CudaArch::UNKNOWN) {
1819 C.getDriver().Diag(clang::diag::err_drv_cuda_bad_gpu_arch) << ArchStr;
1820 Error = true;
1821 } else if (GpuArchs.insert(Arch).second)
1822 GpuArchList.push_back(Arch);
1823 }
1824
1825 // Default to sm_20 which is the lowest common denominator for supported
1826 // GPUs.
1827 // sm_20 code should work correctly, if suboptimally, on all newer GPUs.
1828 if (GpuArchList.empty())
1829 GpuArchList.push_back(CudaArch::SM_20);
1830
1831 return Error;
1832 }
1833 };
1834
Samuel Antao28c4f182016-10-27 17:08:03 +00001835 /// OpenMP action builder. The host bitcode is passed to the device frontend
1836 /// and all the device linked images are passed to the host link phase.
1837 class OpenMPActionBuilder final : public DeviceActionBuilder {
1838 /// The OpenMP actions for the current input.
1839 ActionList OpenMPDeviceActions;
1840
1841 /// The linker inputs obtained for each toolchain.
1842 SmallVector<ActionList, 8> DeviceLinkerInputs;
1843
1844 public:
1845 OpenMPActionBuilder(Compilation &C, DerivedArgList &Args,
1846 const Driver::InputList &Inputs)
1847 : DeviceActionBuilder(C, Args, Inputs, Action::OFK_OpenMP) {}
1848
1849 ActionBuilderReturnCode
1850 getDeviceDependences(OffloadAction::DeviceDependences &DA,
1851 phases::ID CurPhase, phases::ID FinalPhase,
1852 PhasesTy &Phases) override {
1853
1854 // We should always have an action for each input.
1855 assert(OpenMPDeviceActions.size() == ToolChains.size() &&
1856 "Number of OpenMP actions and toolchains do not match.");
1857
1858 // The host only depends on device action in the linking phase, when all
1859 // the device images have to be embedded in the host image.
1860 if (CurPhase == phases::Link) {
1861 assert(ToolChains.size() == DeviceLinkerInputs.size() &&
1862 "Toolchains and linker inputs sizes do not match.");
1863 auto LI = DeviceLinkerInputs.begin();
1864 for (auto *A : OpenMPDeviceActions) {
1865 LI->push_back(A);
1866 ++LI;
1867 }
1868
1869 // We passed the device action as a host dependence, so we don't need to
1870 // do anything else with them.
1871 OpenMPDeviceActions.clear();
1872 return ABRT_Success;
1873 }
1874
1875 // By default, we produce an action for each device arch.
1876 for (Action *&A : OpenMPDeviceActions)
1877 A = C.getDriver().ConstructPhaseAction(C, Args, CurPhase, A);
1878
1879 return ABRT_Success;
1880 }
1881
1882 ActionBuilderReturnCode addDeviceDepences(Action *HostAction) override {
1883
1884 // If this is an input action replicate it for each OpenMP toolchain.
1885 if (auto *IA = dyn_cast<InputAction>(HostAction)) {
1886 OpenMPDeviceActions.clear();
1887 for (unsigned I = 0; I < ToolChains.size(); ++I)
1888 OpenMPDeviceActions.push_back(
1889 C.MakeAction<InputAction>(IA->getInputArg(), IA->getType()));
1890 return ABRT_Success;
1891 }
1892
Samuel Antaofab4f372016-10-27 18:00:51 +00001893 // If this is an unbundling action use it as is for each OpenMP toolchain.
1894 if (auto *UA = dyn_cast<OffloadUnbundlingJobAction>(HostAction)) {
1895 OpenMPDeviceActions.clear();
1896 for (unsigned I = 0; I < ToolChains.size(); ++I) {
1897 OpenMPDeviceActions.push_back(UA);
1898 UA->registerDependentActionInfo(
1899 ToolChains[I], /*BoundArch=*/StringRef(), Action::OFK_OpenMP);
1900 }
1901 return ABRT_Success;
1902 }
1903
Samuel Antao28c4f182016-10-27 17:08:03 +00001904 // When generating code for OpenMP we use the host compile phase result as
1905 // a dependence to the device compile phase so that it can learn what
1906 // declarations should be emitted. However, this is not the only use for
1907 // the host action, so we prevent it from being collapsed.
1908 if (isa<CompileJobAction>(HostAction)) {
1909 HostAction->setCannotBeCollapsedWithNextDependentAction();
1910 assert(ToolChains.size() == OpenMPDeviceActions.size() &&
1911 "Toolchains and device action sizes do not match.");
1912 OffloadAction::HostDependence HDep(
1913 *HostAction, *C.getSingleOffloadToolChain<Action::OFK_Host>(),
1914 /*BoundArch=*/nullptr, Action::OFK_OpenMP);
1915 auto TC = ToolChains.begin();
1916 for (Action *&A : OpenMPDeviceActions) {
1917 assert(isa<CompileJobAction>(A));
1918 OffloadAction::DeviceDependences DDep;
1919 DDep.add(*A, **TC, /*BoundArch=*/nullptr, Action::OFK_OpenMP);
1920 A = C.MakeAction<OffloadAction>(HDep, DDep);
1921 ++TC;
1922 }
1923 }
1924 return ABRT_Success;
1925 }
1926
Samuel Antao69d6f312016-10-27 17:50:43 +00001927 void appendTopLevelActions(ActionList &AL) override {
1928 if (OpenMPDeviceActions.empty())
1929 return;
1930
1931 // We should always have an action for each input.
1932 assert(OpenMPDeviceActions.size() == ToolChains.size() &&
1933 "Number of OpenMP actions and toolchains do not match.");
1934
1935 // Append all device actions followed by the proper offload action.
1936 auto TI = ToolChains.begin();
1937 for (auto *A : OpenMPDeviceActions) {
1938 OffloadAction::DeviceDependences Dep;
1939 Dep.add(*A, **TI, /*BoundArch=*/nullptr, Action::OFK_OpenMP);
1940 AL.push_back(C.MakeAction<OffloadAction>(Dep, A->getType()));
1941 ++TI;
1942 }
1943 // We no longer need the action stored in this builder.
1944 OpenMPDeviceActions.clear();
1945 }
1946
Samuel Antao28c4f182016-10-27 17:08:03 +00001947 void appendLinkDependences(OffloadAction::DeviceDependences &DA) override {
1948 assert(ToolChains.size() == DeviceLinkerInputs.size() &&
1949 "Toolchains and linker inputs sizes do not match.");
1950
1951 // Append a new link action for each device.
1952 auto TC = ToolChains.begin();
1953 for (auto &LI : DeviceLinkerInputs) {
1954 auto *DeviceLinkAction =
1955 C.MakeAction<LinkJobAction>(LI, types::TY_Image);
1956 DA.add(*DeviceLinkAction, **TC, /*BoundArch=*/nullptr,
1957 Action::OFK_OpenMP);
1958 ++TC;
1959 }
1960 }
1961
1962 bool initialize() override {
1963 // Get the OpenMP toolchains. If we don't get any, the action builder will
1964 // know there is nothing to do related to OpenMP offloading.
1965 auto OpenMPTCRange = C.getOffloadToolChains<Action::OFK_OpenMP>();
1966 for (auto TI = OpenMPTCRange.first, TE = OpenMPTCRange.second; TI != TE;
1967 ++TI)
1968 ToolChains.push_back(TI->second);
1969
1970 DeviceLinkerInputs.resize(ToolChains.size());
1971 return false;
1972 }
Samuel Antao69d6f312016-10-27 17:50:43 +00001973
1974 bool canUseBundlerUnbundler() const override {
1975 // OpenMP should use bundled files whenever possible.
1976 return true;
1977 }
Samuel Antao28c4f182016-10-27 17:08:03 +00001978 };
1979
1980 ///
1981 /// TODO: Add the implementation for other specialized builders here.
1982 ///
Samuel Antao64e965e2016-09-30 15:34:19 +00001983
1984 /// Specialized builders being used by this offloading action builder.
1985 SmallVector<DeviceActionBuilder *, 4> SpecializedBuilders;
1986
Samuel Antao69d6f312016-10-27 17:50:43 +00001987 /// Flag set to true if all valid builders allow file bundling/unbundling.
1988 bool CanUseBundler;
1989
Samuel Antao64e965e2016-09-30 15:34:19 +00001990public:
1991 OffloadingActionBuilder(Compilation &C, DerivedArgList &Args,
1992 const Driver::InputList &Inputs)
Samuel Antao10e905c2016-10-27 01:08:58 +00001993 : C(C) {
Samuel Antao64e965e2016-09-30 15:34:19 +00001994 // Create a specialized builder for each device toolchain.
1995
1996 IsValid = true;
1997
1998 // Create a specialized builder for CUDA.
1999 SpecializedBuilders.push_back(new CudaActionBuilder(C, Args, Inputs));
2000
Samuel Antao28c4f182016-10-27 17:08:03 +00002001 // Create a specialized builder for OpenMP.
2002 SpecializedBuilders.push_back(new OpenMPActionBuilder(C, Args, Inputs));
2003
Samuel Antao64e965e2016-09-30 15:34:19 +00002004 //
2005 // TODO: Build other specialized builders here.
2006 //
2007
Samuel Antao69d6f312016-10-27 17:50:43 +00002008 // Initialize all the builders, keeping track of errors. If all valid
2009 // builders agree that we can use bundling, set the flag to true.
2010 unsigned ValidBuilders = 0u;
2011 unsigned ValidBuildersSupportingBundling = 0u;
2012 for (auto *SB : SpecializedBuilders) {
Samuel Antao64e965e2016-09-30 15:34:19 +00002013 IsValid = IsValid && !SB->initialize();
Samuel Antao69d6f312016-10-27 17:50:43 +00002014
2015 // Update the counters if the builder is valid.
2016 if (SB->isValid()) {
2017 ++ValidBuilders;
2018 if (SB->canUseBundlerUnbundler())
2019 ++ValidBuildersSupportingBundling;
2020 }
2021 }
2022 CanUseBundler =
2023 ValidBuilders && ValidBuilders == ValidBuildersSupportingBundling;
Artem Belevichf981e30b2016-08-02 22:37:47 +00002024 }
Justin Lebardc3c5042016-04-19 02:27:07 +00002025
Samuel Antao64e965e2016-09-30 15:34:19 +00002026 ~OffloadingActionBuilder() {
2027 for (auto *SB : SpecializedBuilders)
2028 delete SB;
Samuel Antaod06239d2016-07-15 23:13:27 +00002029 }
Artem Belevich0ff05cd2015-07-13 23:27:56 +00002030
Samuel Antao64e965e2016-09-30 15:34:19 +00002031 /// Generate an action that adds device dependences (if any) to a host action.
2032 /// If no device dependence actions exist, just return the host action \a
2033 /// HostAction. If an error is found or if no builder requires the host action
2034 /// to be generated, return nullptr.
2035 Action *
2036 addDeviceDependencesToHostAction(Action *HostAction, const Arg *InputArg,
2037 phases::ID CurPhase, phases::ID FinalPhase,
2038 DeviceActionBuilder::PhasesTy &Phases) {
2039 if (!IsValid)
2040 return nullptr;
Justin Lebar7bf77982016-01-11 23:27:13 +00002041
Samuel Antao64e965e2016-09-30 15:34:19 +00002042 if (SpecializedBuilders.empty())
2043 return HostAction;
2044
2045 assert(HostAction && "Invalid host action!");
2046
2047 OffloadAction::DeviceDependences DDeps;
2048 // Check if all the programming models agree we should not emit the host
2049 // action. Also, keep track of the offloading kinds employed.
2050 auto &OffloadKind = InputArgToOffloadKindMap[InputArg];
2051 unsigned InactiveBuilders = 0u;
2052 unsigned IgnoringBuilders = 0u;
2053 for (auto *SB : SpecializedBuilders) {
2054 if (!SB->isValid()) {
2055 ++InactiveBuilders;
2056 continue;
2057 }
2058
Samuel Antao28c4f182016-10-27 17:08:03 +00002059 auto RetCode =
2060 SB->getDeviceDependences(DDeps, CurPhase, FinalPhase, Phases);
Samuel Antao64e965e2016-09-30 15:34:19 +00002061
2062 // If the builder explicitly says the host action should be ignored,
2063 // we need to increment the variable that tracks the builders that request
2064 // the host object to be ignored.
2065 if (RetCode == DeviceActionBuilder::ABRT_Ignore_Host)
2066 ++IgnoringBuilders;
2067
2068 // Unless the builder was inactive for this action, we have to record the
2069 // offload kind because the host will have to use it.
2070 if (RetCode != DeviceActionBuilder::ABRT_Inactive)
2071 OffloadKind |= SB->getAssociatedOffloadKind();
2072 }
2073
2074 // If all builders agree that the host object should be ignored, just return
2075 // nullptr.
2076 if (IgnoringBuilders &&
2077 SpecializedBuilders.size() == (InactiveBuilders + IgnoringBuilders))
2078 return nullptr;
2079
2080 if (DDeps.getActions().empty())
2081 return HostAction;
2082
2083 // We have dependences we need to bundle together. We use an offload action
2084 // for that.
2085 OffloadAction::HostDependence HDep(
2086 *HostAction, *C.getSingleOffloadToolChain<Action::OFK_Host>(),
2087 /*BoundArch=*/nullptr, DDeps);
2088 return C.MakeAction<OffloadAction>(HDep, DDeps);
Artem Belevich0ff05cd2015-07-13 23:27:56 +00002089 }
2090
Samuel Antao64e965e2016-09-30 15:34:19 +00002091 /// Generate an action that adds a host dependence to a device action. The
2092 /// results will be kept in this action builder. Return true if an error was
2093 /// found.
Samuel Antaofab4f372016-10-27 18:00:51 +00002094 bool addHostDependenceToDeviceActions(Action *&HostAction,
Samuel Antao64e965e2016-09-30 15:34:19 +00002095 const Arg *InputArg) {
2096 if (!IsValid)
2097 return true;
Artem Belevich0ff05cd2015-07-13 23:27:56 +00002098
Samuel Antaofab4f372016-10-27 18:00:51 +00002099 // If we are supporting bundling/unbundling and the current action is an
2100 // input action of non-source file, we replace the host action by the
2101 // unbundling action. The bundler tool has the logic to detect if an input
2102 // is a bundle or not and if the input is not a bundle it assumes it is a
2103 // host file. Therefore it is safe to create an unbundling action even if
2104 // the input is not a bundle.
2105 if (CanUseBundler && isa<InputAction>(HostAction) &&
2106 InputArg->getOption().getKind() == llvm::opt::Option::InputClass &&
2107 !types::isSrcFile(HostAction->getType())) {
2108 auto UnbundlingHostAction =
2109 C.MakeAction<OffloadUnbundlingJobAction>(HostAction);
2110 UnbundlingHostAction->registerDependentActionInfo(
2111 C.getSingleOffloadToolChain<Action::OFK_Host>(),
2112 /*BoundArch=*/StringRef(), Action::OFK_Host);
2113 HostAction = UnbundlingHostAction;
2114 }
2115
Samuel Antao64e965e2016-09-30 15:34:19 +00002116 assert(HostAction && "Invalid host action!");
Artem Belevich0ff05cd2015-07-13 23:27:56 +00002117
Samuel Antao64e965e2016-09-30 15:34:19 +00002118 // Register the offload kinds that are used.
2119 auto &OffloadKind = InputArgToOffloadKindMap[InputArg];
2120 for (auto *SB : SpecializedBuilders) {
2121 if (!SB->isValid())
2122 continue;
Artem Belevich0ff05cd2015-07-13 23:27:56 +00002123
Samuel Antao64e965e2016-09-30 15:34:19 +00002124 auto RetCode = SB->addDeviceDepences(HostAction);
Artem Belevich0ff05cd2015-07-13 23:27:56 +00002125
Samuel Antao64e965e2016-09-30 15:34:19 +00002126 // Host dependences for device actions are not compatible with that same
2127 // action being ignored.
2128 assert(RetCode != DeviceActionBuilder::ABRT_Ignore_Host &&
2129 "Host dependence not expected to be ignored.!");
Samuel Antaod06239d2016-07-15 23:13:27 +00002130
Samuel Antao64e965e2016-09-30 15:34:19 +00002131 // Unless the builder was inactive for this action, we have to record the
2132 // offload kind because the host will have to use it.
2133 if (RetCode != DeviceActionBuilder::ABRT_Inactive)
2134 OffloadKind |= SB->getAssociatedOffloadKind();
2135 }
Artem Belevich0ff05cd2015-07-13 23:27:56 +00002136
Samuel Antao64e965e2016-09-30 15:34:19 +00002137 return false;
2138 }
2139
Samuel Antao69d6f312016-10-27 17:50:43 +00002140 /// Add the offloading top level actions to the provided action list. This
2141 /// function can replace the host action by a bundling action if the
2142 /// programming models allow it.
Samuel Antao64e965e2016-09-30 15:34:19 +00002143 bool appendTopLevelActions(ActionList &AL, Action *HostAction,
2144 const Arg *InputArg) {
Samuel Antao69d6f312016-10-27 17:50:43 +00002145 // Get the device actions to be appended.
2146 ActionList OffloadAL;
Samuel Antao64e965e2016-09-30 15:34:19 +00002147 for (auto *SB : SpecializedBuilders) {
2148 if (!SB->isValid())
2149 continue;
Samuel Antao69d6f312016-10-27 17:50:43 +00002150 SB->appendTopLevelActions(OffloadAL);
Samuel Antao64e965e2016-09-30 15:34:19 +00002151 }
2152
Samuel Antao69d6f312016-10-27 17:50:43 +00002153 // If we can use the bundler, replace the host action by the bundling one in
2154 // the resulting list. Otherwise, just append the device actions.
2155 if (CanUseBundler && !OffloadAL.empty()) {
2156 // Add the host action to the list in order to create the bundling action.
2157 OffloadAL.push_back(HostAction);
2158
2159 // We expect that the host action was just appended to the action list
2160 // before this method was called.
2161 assert(HostAction == AL.back() && "Host action not in the list??");
2162 HostAction = C.MakeAction<OffloadBundlingJobAction>(OffloadAL);
2163 AL.back() = HostAction;
2164 } else
2165 AL.append(OffloadAL.begin(), OffloadAL.end());
2166
Samuel Antao64e965e2016-09-30 15:34:19 +00002167 // Propagate to the current host action (if any) the offload information
2168 // associated with the current input.
2169 if (HostAction)
2170 HostAction->propagateHostOffloadInfo(InputArgToOffloadKindMap[InputArg],
2171 /*BoundArch=*/nullptr);
Samuel Antao64e965e2016-09-30 15:34:19 +00002172 return false;
Artem Belevich0ff05cd2015-07-13 23:27:56 +00002173 }
Artem Belevich5bde4e02015-07-20 20:02:54 +00002174
Samuel Antao64e965e2016-09-30 15:34:19 +00002175 /// Processes the host linker action. This currently consists of replacing it
2176 /// with an offload action if there are device link objects and propagate to
2177 /// the host action all the offload kinds used in the current compilation. The
2178 /// resulting action is returned.
2179 Action *processHostLinkAction(Action *HostAction) {
2180 // Add all the dependences from the device linking actions.
2181 OffloadAction::DeviceDependences DDeps;
2182 for (auto *SB : SpecializedBuilders) {
2183 if (!SB->isValid())
2184 continue;
Justin Lebar21e5d4f2016-01-14 21:41:27 +00002185
Samuel Antao64e965e2016-09-30 15:34:19 +00002186 SB->appendLinkDependences(DDeps);
Justin Lebar21e5d4f2016-01-14 21:41:27 +00002187 }
Samuel Antaod06239d2016-07-15 23:13:27 +00002188
Samuel Antao64e965e2016-09-30 15:34:19 +00002189 // Calculate all the offload kinds used in the current compilation.
2190 unsigned ActiveOffloadKinds = 0u;
2191 for (auto &I : InputArgToOffloadKindMap)
2192 ActiveOffloadKinds |= I.second;
2193
2194 // If we don't have device dependencies, we don't have to create an offload
2195 // action.
2196 if (DDeps.getActions().empty()) {
2197 // Propagate all the active kinds to host action. Given that it is a link
2198 // action it is assumed to depend on all actions generated so far.
2199 HostAction->propagateHostOffloadInfo(ActiveOffloadKinds,
2200 /*BoundArch=*/nullptr);
2201 return HostAction;
2202 }
2203
2204 // Create the offload action with all dependences. When an offload action
2205 // is created the kinds are propagated to the host action, so we don't have
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00002206 // to do that explicitly here.
Samuel Antao64e965e2016-09-30 15:34:19 +00002207 OffloadAction::HostDependence HDep(
2208 *HostAction, *C.getSingleOffloadToolChain<Action::OFK_Host>(),
2209 /*BoundArch*/ nullptr, ActiveOffloadKinds);
2210 return C.MakeAction<OffloadAction>(HDep, DDeps);
2211 }
2212};
2213} // anonymous namespace.
Artem Belevich0ff05cd2015-07-13 23:27:56 +00002214
Justin Lebar0f3474c2016-02-11 02:00:50 +00002215void Driver::BuildActions(Compilation &C, DerivedArgList &Args,
2216 const InputList &Inputs, ActionList &Actions) const {
Chad Rosierecdede82011-08-12 22:08:57 +00002217 llvm::PrettyStackTraceString CrashInfo("Building compilation actions");
Joerg Sonnenbergerb86f5f42011-03-06 23:31:01 +00002218
Daniel Dunbar34c41872009-03-13 00:17:48 +00002219 if (!SuppressMissingInputWarning && Inputs.empty()) {
Daniel Dunbarbfeec742009-03-12 23:55:14 +00002220 Diag(clang::diag::err_drv_no_input_files);
2221 return;
2222 }
2223
Chad Rosier7742b5d2011-07-27 23:36:45 +00002224 Arg *FinalPhaseArg;
2225 phases::ID FinalPhase = getFinalPhase(Args, &FinalPhaseArg);
Daniel Dunbarbfeec742009-03-12 23:55:14 +00002226
Rafael Espindolae8025642013-08-25 14:27:09 +00002227 if (FinalPhase == phases::Link && Args.hasArg(options::OPT_emit_llvm)) {
2228 Diag(clang::diag::err_drv_emit_llvm_link);
2229 }
2230
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00002231 // Reject -Z* at the top level, these options should never have been exposed
2232 // by gcc.
Daniel Dunbardd765242009-03-26 16:12:09 +00002233 if (Arg *A = Args.getLastArg(options::OPT_Z_Joined))
Daniel Dunbar0e759942009-03-20 06:14:23 +00002234 Diag(clang::diag::err_drv_use_of_Z_option) << A->getAsString(Args);
Daniel Dunbarbfeec742009-03-12 23:55:14 +00002235
Hans Wennborg13b7fe72013-08-12 23:26:25 +00002236 // Diagnose misuse of /Fo.
2237 if (Arg *A = Args.getLastArg(options::OPT__SLASH_Fo)) {
Hans Wennborg13b7fe72013-08-12 23:26:25 +00002238 StringRef V = A->getValue();
Hans Wennborg61647532014-11-17 19:16:36 +00002239 if (Inputs.size() > 1 && !V.empty() &&
2240 !llvm::sys::path::is_separator(V.back())) {
Hans Wennborg13b7fe72013-08-12 23:26:25 +00002241 // Check whether /Fo tries to name an output file for multiple inputs.
Hans Wennborg9c1659b2013-10-18 22:49:04 +00002242 Diag(clang::diag::err_drv_out_file_argument_with_multiple_sources)
Douglas Katzmana67e50c2015-06-26 15:47:46 +00002243 << A->getSpelling() << V;
Hans Wennborg13b7fe72013-08-12 23:26:25 +00002244 Args.eraseArg(options::OPT__SLASH_Fo);
2245 }
2246 }
2247
Hans Wennborg9c1659b2013-10-18 22:49:04 +00002248 // Diagnose misuse of /Fa.
2249 if (Arg *A = Args.getLastArg(options::OPT__SLASH_Fa)) {
2250 StringRef V = A->getValue();
Hans Wennborg61647532014-11-17 19:16:36 +00002251 if (Inputs.size() > 1 && !V.empty() &&
2252 !llvm::sys::path::is_separator(V.back())) {
Hans Wennborg9c1659b2013-10-18 22:49:04 +00002253 // Check whether /Fa tries to name an asm file for multiple inputs.
2254 Diag(clang::diag::err_drv_out_file_argument_with_multiple_sources)
Douglas Katzmana67e50c2015-06-26 15:47:46 +00002255 << A->getSpelling() << V;
Hans Wennborg9c1659b2013-10-18 22:49:04 +00002256 Args.eraseArg(options::OPT__SLASH_Fa);
2257 }
2258 }
2259
Ehsan Akhgari81f36b72014-09-11 18:16:21 +00002260 // Diagnose misuse of /o.
2261 if (Arg *A = Args.getLastArg(options::OPT__SLASH_o)) {
2262 if (A->getValue()[0] == '\0') {
2263 // It has to have a value.
2264 Diag(clang::diag::err_drv_missing_argument) << A->getSpelling() << 1;
2265 Args.eraseArg(options::OPT__SLASH_o);
2266 }
2267 }
2268
Nico Weber2ca4be92016-03-01 23:16:44 +00002269 // Diagnose unsupported forms of /Yc /Yu. Ignore /Yc/Yu for now if:
2270 // * no filename after it
2271 // * both /Yc and /Yu passed but with different filenames
2272 // * corresponding file not also passed as /FI
2273 Arg *YcArg = Args.getLastArg(options::OPT__SLASH_Yc);
2274 Arg *YuArg = Args.getLastArg(options::OPT__SLASH_Yu);
2275 if (YcArg && YcArg->getValue()[0] == '\0') {
2276 Diag(clang::diag::warn_drv_ycyu_no_arg_clang_cl) << YcArg->getSpelling();
2277 Args.eraseArg(options::OPT__SLASH_Yc);
2278 YcArg = nullptr;
2279 }
2280 if (YuArg && YuArg->getValue()[0] == '\0') {
2281 Diag(clang::diag::warn_drv_ycyu_no_arg_clang_cl) << YuArg->getSpelling();
2282 Args.eraseArg(options::OPT__SLASH_Yu);
2283 YuArg = nullptr;
2284 }
2285 if (YcArg && YuArg && strcmp(YcArg->getValue(), YuArg->getValue()) != 0) {
2286 Diag(clang::diag::warn_drv_ycyu_different_arg_clang_cl);
2287 Args.eraseArg(options::OPT__SLASH_Yc);
2288 Args.eraseArg(options::OPT__SLASH_Yu);
2289 YcArg = YuArg = nullptr;
2290 }
2291 if (YcArg || YuArg) {
2292 StringRef Val = YcArg ? YcArg->getValue() : YuArg->getValue();
2293 bool FoundMatchingInclude = false;
2294 for (const Arg *Inc : Args.filtered(options::OPT_include)) {
2295 // FIXME: Do case-insensitive matching and consider / and \ as equal.
2296 if (Inc->getValue() == Val)
2297 FoundMatchingInclude = true;
2298 }
2299 if (!FoundMatchingInclude) {
2300 Diag(clang::diag::warn_drv_ycyu_no_fi_arg_clang_cl)
2301 << (YcArg ? YcArg : YuArg)->getSpelling();
2302 Args.eraseArg(options::OPT__SLASH_Yc);
2303 Args.eraseArg(options::OPT__SLASH_Yu);
2304 YcArg = YuArg = nullptr;
2305 }
2306 }
2307 if (YcArg && Inputs.size() > 1) {
2308 Diag(clang::diag::warn_drv_yc_multiple_inputs_clang_cl);
2309 Args.eraseArg(options::OPT__SLASH_Yc);
2310 YcArg = nullptr;
2311 }
2312 if (Args.hasArg(options::OPT__SLASH_Y_)) {
2313 // /Y- disables all pch handling. Rather than check for it everywhere,
2314 // just remove clang-cl pch-related flags here.
2315 Args.eraseArg(options::OPT__SLASH_Fp);
2316 Args.eraseArg(options::OPT__SLASH_Yc);
2317 Args.eraseArg(options::OPT__SLASH_Yu);
2318 YcArg = YuArg = nullptr;
2319 }
Nico Weber2ca4be92016-03-01 23:16:44 +00002320
Samuel Antao64e965e2016-09-30 15:34:19 +00002321 // Builder to be used to build offloading actions.
2322 OffloadingActionBuilder OffloadBuilder(C, Args, Inputs);
Samuel Antaod06239d2016-07-15 23:13:27 +00002323
Daniel Dunbar65229332009-03-13 11:38:42 +00002324 // Construct the actions to perform.
2325 ActionList LinkerInputs;
Alp Toker965f8822013-11-27 05:22:15 +00002326
Matthew Curtis7ab8b2b2013-03-07 12:32:26 +00002327 llvm::SmallVector<phases::ID, phases::MaxNumberOfPhases> PL;
Artem Belevich5bde4e02015-07-20 20:02:54 +00002328 for (auto &I : Inputs) {
2329 types::ID InputType = I.first;
2330 const Arg *InputArg = I.second;
Daniel Dunbar65229332009-03-13 11:38:42 +00002331
Matthew Curtis7ab8b2b2013-03-07 12:32:26 +00002332 PL.clear();
2333 types::getCompilationPhases(InputType, PL);
Daniel Dunbar65229332009-03-13 11:38:42 +00002334
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00002335 // If the first step comes after the final phase we are doing as part of
2336 // this compilation, warn the user about it.
Matthew Curtis7ab8b2b2013-03-07 12:32:26 +00002337 phases::ID InitialPhase = PL[0];
Daniel Dunbar65229332009-03-13 11:38:42 +00002338 if (InitialPhase > FinalPhase) {
Daniel Dunbaradc5c7c2009-03-19 07:57:08 +00002339 // Claim here to avoid the more general unused warning.
2340 InputArg->claim();
Daniel Dunbar07806ca2009-09-17 04:13:26 +00002341
Daniel Dunbar2db3e732011-04-20 15:44:48 +00002342 // Suppress all unused style warnings with -Qunused-arguments
2343 if (Args.hasArg(options::OPT_Qunused_arguments))
2344 continue;
2345
Richard Smith403f76e2012-08-06 04:09:06 +00002346 // Special case when final phase determined by binary name, rather than
2347 // by a command-line argument with a corresponding Arg.
Hans Wennborg70850d82013-07-18 20:29:38 +00002348 if (CCCIsCPP())
Richard Smith403f76e2012-08-06 04:09:06 +00002349 Diag(clang::diag::warn_drv_input_file_unused_by_cpp)
Douglas Katzmana67e50c2015-06-26 15:47:46 +00002350 << InputArg->getAsString(Args) << getPhaseName(InitialPhase);
Daniel Dunbar07806ca2009-09-17 04:13:26 +00002351 // Special case '-E' warning on a previously preprocessed file to make
2352 // more sense.
Richard Smith403f76e2012-08-06 04:09:06 +00002353 else if (InitialPhase == phases::Compile &&
2354 FinalPhase == phases::Preprocess &&
2355 getPreprocessedType(InputType) == types::TY_INVALID)
Daniel Dunbar07806ca2009-09-17 04:13:26 +00002356 Diag(clang::diag::warn_drv_preprocessed_input_file_unused)
Douglas Katzmana67e50c2015-06-26 15:47:46 +00002357 << InputArg->getAsString(Args) << !!FinalPhaseArg
2358 << (FinalPhaseArg ? FinalPhaseArg->getOption().getName() : "");
Daniel Dunbar07806ca2009-09-17 04:13:26 +00002359 else
2360 Diag(clang::diag::warn_drv_input_file_unused)
Douglas Katzmana67e50c2015-06-26 15:47:46 +00002361 << InputArg->getAsString(Args) << getPhaseName(InitialPhase)
2362 << !!FinalPhaseArg
2363 << (FinalPhaseArg ? FinalPhaseArg->getOption().getName() : "");
Daniel Dunbar65229332009-03-13 11:38:42 +00002364 continue;
2365 }
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00002366
Nico Weberad2d8f32016-04-21 19:59:10 +00002367 if (YcArg) {
2368 // Add a separate precompile phase for the compile phase.
2369 if (FinalPhase >= phases::Compile) {
Richard Smith8cd452d2016-08-30 18:55:16 +00002370 const types::ID HeaderType = lookupHeaderTypeForSourceType(InputType);
Nico Weberad2d8f32016-04-21 19:59:10 +00002371 llvm::SmallVector<phases::ID, phases::MaxNumberOfPhases> PCHPL;
Richard Smith8cd452d2016-08-30 18:55:16 +00002372 types::getCompilationPhases(HeaderType, PCHPL);
Nico Weberad2d8f32016-04-21 19:59:10 +00002373 Arg *PchInputArg = MakeInputArg(Args, Opts, YcArg->getValue());
2374
2375 // Build the pipeline for the pch file.
Richard Smith8cd452d2016-08-30 18:55:16 +00002376 Action *ClangClPch =
2377 C.MakeAction<InputAction>(*PchInputArg, HeaderType);
Nico Weberad2d8f32016-04-21 19:59:10 +00002378 for (phases::ID Phase : PCHPL)
2379 ClangClPch = ConstructPhaseAction(C, Args, Phase, ClangClPch);
2380 assert(ClangClPch);
2381 Actions.push_back(ClangClPch);
2382 // The driver currently exits after the first failed command. This
2383 // relies on that behavior, to make sure if the pch generation fails,
2384 // the main compilation won't run.
2385 }
2386 }
2387
Daniel Dunbar65229332009-03-13 11:38:42 +00002388 // Build the pipeline for this file.
Justin Lebar41094612016-01-11 23:07:27 +00002389 Action *Current = C.MakeAction<InputAction>(*InputArg, InputType);
Samuel Antao64e965e2016-09-30 15:34:19 +00002390
2391 // Use the current host action in any of the offloading actions, if
2392 // required.
2393 if (OffloadBuilder.addHostDependenceToDeviceActions(Current, InputArg))
2394 break;
2395
Douglas Katzmana67e50c2015-06-26 15:47:46 +00002396 for (SmallVectorImpl<phases::ID>::iterator i = PL.begin(), e = PL.end();
2397 i != e; ++i) {
Matthew Curtis7ab8b2b2013-03-07 12:32:26 +00002398 phases::ID Phase = *i;
Daniel Dunbar65229332009-03-13 11:38:42 +00002399
2400 // We are done if this step is past what the user requested.
2401 if (Phase > FinalPhase)
2402 break;
2403
Samuel Antao64e965e2016-09-30 15:34:19 +00002404 // Add any offload action the host action depends on.
2405 Current = OffloadBuilder.addDeviceDependencesToHostAction(
2406 Current, InputArg, Phase, FinalPhase, PL);
2407 if (!Current)
2408 break;
2409
Daniel Dunbar65229332009-03-13 11:38:42 +00002410 // Queue linker inputs.
2411 if (Phase == phases::Link) {
Matthew Curtis7ab8b2b2013-03-07 12:32:26 +00002412 assert((i + 1) == e && "linking must be final compilation step.");
Justin Lebar41094612016-01-11 23:07:27 +00002413 LinkerInputs.push_back(Current);
2414 Current = nullptr;
Daniel Dunbar65229332009-03-13 11:38:42 +00002415 break;
2416 }
2417
Samuel Antao64e965e2016-09-30 15:34:19 +00002418 // Otherwise construct the appropriate action.
2419 auto *NewCurrent = ConstructPhaseAction(C, Args, Phase, Current);
2420
2421 // We didn't create a new action, so we will just move to the next phase.
2422 if (NewCurrent == Current)
Daniel Dunbar13864952009-03-24 20:17:30 +00002423 continue;
2424
Samuel Antao64e965e2016-09-30 15:34:19 +00002425 Current = NewCurrent;
Artem Belevich0ff05cd2015-07-13 23:27:56 +00002426
Samuel Antao64e965e2016-09-30 15:34:19 +00002427 // Use the current host action in any of the offloading actions, if
2428 // required.
2429 if (OffloadBuilder.addHostDependenceToDeviceActions(Current, InputArg))
2430 break;
Artem Belevich0ff05cd2015-07-13 23:27:56 +00002431
Daniel Dunbar65229332009-03-13 11:38:42 +00002432 if (Current->getType() == types::TY_Nothing)
2433 break;
2434 }
2435
Samuel Antao64e965e2016-09-30 15:34:19 +00002436 // If we ended with something, add to the output list.
2437 if (Current)
Justin Lebar41094612016-01-11 23:07:27 +00002438 Actions.push_back(Current);
Samuel Antao64e965e2016-09-30 15:34:19 +00002439
2440 // Add any top level actions generated for offloading.
2441 OffloadBuilder.appendTopLevelActions(Actions, Current, InputArg);
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00002442 }
Daniel Dunbar65229332009-03-13 11:38:42 +00002443
Samuel Antao64e965e2016-09-30 15:34:19 +00002444 // Add a link action if necessary.
Samuel Antaod06239d2016-07-15 23:13:27 +00002445 if (!LinkerInputs.empty()) {
Samuel Antao64e965e2016-09-30 15:34:19 +00002446 Action *LA = C.MakeAction<LinkJobAction>(LinkerInputs, types::TY_Image);
2447 LA = OffloadBuilder.processHostLinkAction(LA);
2448 Actions.push_back(LA);
Samuel Antaod06239d2016-07-15 23:13:27 +00002449 }
Daniel Dunbarc7a67b72009-12-22 23:19:32 +00002450
2451 // If we are linking, claim any options which are obviously only used for
2452 // compilation.
Hans Wennborga8ef14f2013-09-17 00:03:41 +00002453 if (FinalPhase == phases::Link && PL.size() == 1) {
Daniel Dunbarc7a67b72009-12-22 23:19:32 +00002454 Args.ClaimAllArgs(options::OPT_CompileOnly_Group);
Hans Wennborga8ef14f2013-09-17 00:03:41 +00002455 Args.ClaimAllArgs(options::OPT_cl_compile_Group);
2456 }
2457
2458 // Claim ignored clang-cl options.
2459 Args.ClaimAllArgs(options::OPT_cl_ignored_Group);
Artem Belevichbaae0932015-07-28 21:01:30 +00002460
Justin Lebardc3c5042016-04-19 02:27:07 +00002461 // Claim --cuda-host-only and --cuda-compile-host-device, which may be passed
2462 // to non-CUDA compilations and should not trigger warnings there.
Artem Belevichbaae0932015-07-28 21:01:30 +00002463 Args.ClaimAllArgs(options::OPT_cuda_host_only);
Justin Lebardc3c5042016-04-19 02:27:07 +00002464 Args.ClaimAllArgs(options::OPT_cuda_compile_host_device);
Daniel Dunbar65229332009-03-13 11:38:42 +00002465}
2466
Justin Lebar0f3474c2016-02-11 02:00:50 +00002467Action *Driver::ConstructPhaseAction(Compilation &C, const ArgList &Args,
2468 phases::ID Phase, Action *Input) const {
Daniel Dunbar2608c542009-03-18 01:38:48 +00002469 llvm::PrettyStackTraceString CrashInfo("Constructing phase actions");
Samuel Antao64e965e2016-09-30 15:34:19 +00002470
2471 // Some types skip the assembler phase (e.g., llvm-bc), but we can't
2472 // encode this in the steps because the intermediate type depends on
2473 // arguments. Just special case here.
2474 if (Phase == phases::Assemble && Input->getType() != types::TY_PP_Asm)
2475 return Input;
2476
Daniel Dunbar65229332009-03-13 11:38:42 +00002477 // Build the appropriate action.
2478 switch (Phase) {
Douglas Katzmana67e50c2015-06-26 15:47:46 +00002479 case phases::Link:
2480 llvm_unreachable("link action invalid here.");
Daniel Dunbar65229332009-03-13 11:38:42 +00002481 case phases::Preprocess: {
Daniel Dunbard67a3222009-03-30 06:36:42 +00002482 types::ID OutputTy;
2483 // -{M, MM} alter the output type.
Daniel Dunbar86aed7d2010-12-08 21:33:40 +00002484 if (Args.hasArg(options::OPT_M, options::OPT_MM)) {
Daniel Dunbard67a3222009-03-30 06:36:42 +00002485 OutputTy = types::TY_Dependencies;
2486 } else {
David Blaikie5d577a22012-06-29 22:03:56 +00002487 OutputTy = Input->getType();
2488 if (!Args.hasFlag(options::OPT_frewrite_includes,
Justin Bognerce8245b2014-06-24 08:01:01 +00002489 options::OPT_fno_rewrite_includes, false) &&
2490 !CCGenDiagnostics)
David Blaikie5d577a22012-06-29 22:03:56 +00002491 OutputTy = types::getPreprocessedType(OutputTy);
Daniel Dunbard67a3222009-03-30 06:36:42 +00002492 assert(OutputTy != types::TY_INVALID &&
2493 "Cannot preprocess this input type!");
2494 }
Justin Lebar41094612016-01-11 23:07:27 +00002495 return C.MakeAction<PreprocessJobAction>(Input, OutputTy);
Daniel Dunbar65229332009-03-13 11:38:42 +00002496 }
Aaron Ballman1f10cc52012-07-31 01:21:00 +00002497 case phases::Precompile: {
Richard Smithdd4ad3d2016-08-30 19:06:26 +00002498 types::ID OutputTy = getPrecompiledType(Input->getType());
2499 assert(OutputTy != types::TY_INVALID &&
2500 "Cannot precompile this input type!");
Aaron Ballman1f10cc52012-07-31 01:21:00 +00002501 if (Args.hasArg(options::OPT_fsyntax_only)) {
2502 // Syntax checks should not emit a PCH file
2503 OutputTy = types::TY_Nothing;
2504 }
Justin Lebar41094612016-01-11 23:07:27 +00002505 return C.MakeAction<PrecompileJobAction>(Input, OutputTy);
Aaron Ballman1f10cc52012-07-31 01:21:00 +00002506 }
Daniel Dunbar65229332009-03-13 11:38:42 +00002507 case phases::Compile: {
David Blaikie486f4402014-08-29 07:25:23 +00002508 if (Args.hasArg(options::OPT_fsyntax_only))
Justin Lebar41094612016-01-11 23:07:27 +00002509 return C.MakeAction<CompileJobAction>(Input, types::TY_Nothing);
David Blaikie486f4402014-08-29 07:25:23 +00002510 if (Args.hasArg(options::OPT_rewrite_objc))
Justin Lebar41094612016-01-11 23:07:27 +00002511 return C.MakeAction<CompileJobAction>(Input, types::TY_RewrittenObjC);
David Blaikie486f4402014-08-29 07:25:23 +00002512 if (Args.hasArg(options::OPT_rewrite_legacy_objc))
Justin Lebar41094612016-01-11 23:07:27 +00002513 return C.MakeAction<CompileJobAction>(Input,
2514 types::TY_RewrittenLegacyObjC);
David Blaikie486f4402014-08-29 07:25:23 +00002515 if (Args.hasArg(options::OPT__analyze, options::OPT__analyze_auto))
Justin Lebar41094612016-01-11 23:07:27 +00002516 return C.MakeAction<AnalyzeJobAction>(Input, types::TY_Plist);
David Blaikie486f4402014-08-29 07:25:23 +00002517 if (Args.hasArg(options::OPT__migrate))
Justin Lebar41094612016-01-11 23:07:27 +00002518 return C.MakeAction<MigrateJobAction>(Input, types::TY_Remap);
David Blaikie486f4402014-08-29 07:25:23 +00002519 if (Args.hasArg(options::OPT_emit_ast))
Justin Lebar41094612016-01-11 23:07:27 +00002520 return C.MakeAction<CompileJobAction>(Input, types::TY_AST);
David Blaikie486f4402014-08-29 07:25:23 +00002521 if (Args.hasArg(options::OPT_module_file_info))
Justin Lebar41094612016-01-11 23:07:27 +00002522 return C.MakeAction<CompileJobAction>(Input, types::TY_ModuleFile);
David Blaikie486f4402014-08-29 07:25:23 +00002523 if (Args.hasArg(options::OPT_verify_pch))
Justin Lebar41094612016-01-11 23:07:27 +00002524 return C.MakeAction<VerifyPCHJobAction>(Input, types::TY_Nothing);
2525 return C.MakeAction<CompileJobAction>(Input, types::TY_LLVM_BC);
Bob Wilson23a55f12014-12-21 07:00:00 +00002526 }
2527 case phases::Backend: {
Teresa Johnson945bc502015-10-15 20:35:53 +00002528 if (isUsingLTO()) {
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00002529 types::ID Output =
Douglas Katzmana67e50c2015-06-26 15:47:46 +00002530 Args.hasArg(options::OPT_S) ? types::TY_LTO_IR : types::TY_LTO_BC;
Justin Lebar41094612016-01-11 23:07:27 +00002531 return C.MakeAction<BackendJobAction>(Input, Output);
David Blaikie486f4402014-08-29 07:25:23 +00002532 }
2533 if (Args.hasArg(options::OPT_emit_llvm)) {
Shuxin Yang4b3c7ff2013-08-23 21:34:57 +00002534 types::ID Output =
Douglas Katzmana67e50c2015-06-26 15:47:46 +00002535 Args.hasArg(options::OPT_S) ? types::TY_LLVM_IR : types::TY_LLVM_BC;
Justin Lebar41094612016-01-11 23:07:27 +00002536 return C.MakeAction<BackendJobAction>(Input, Output);
Daniel Dunbar65229332009-03-13 11:38:42 +00002537 }
Justin Lebar41094612016-01-11 23:07:27 +00002538 return C.MakeAction<BackendJobAction>(Input, types::TY_PP_Asm);
Daniel Dunbar65229332009-03-13 11:38:42 +00002539 }
2540 case phases::Assemble:
Justin Lebar21e5d4f2016-01-14 21:41:27 +00002541 return C.MakeAction<AssembleJobAction>(std::move(Input), types::TY_Object);
Daniel Dunbar65229332009-03-13 11:38:42 +00002542 }
2543
David Blaikie83d382b2011-09-23 05:06:16 +00002544 llvm_unreachable("invalid phase in ConstructPhaseAction");
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00002545}
2546
Daniel Dunbarf0eddb82009-03-18 02:55:38 +00002547void Driver::BuildJobs(Compilation &C) const {
Daniel Dunbar2608c542009-03-18 01:38:48 +00002548 llvm::PrettyStackTraceString CrashInfo("Building compilation jobs");
Daniel Dunbare75d8342009-03-16 06:56:51 +00002549
2550 Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o);
2551
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00002552 // It is an error to provide a -o option if we are making multiple output
2553 // files.
Daniel Dunbare75d8342009-03-16 06:56:51 +00002554 if (FinalOutput) {
2555 unsigned NumOutputs = 0;
Saleem Abdulrasoolda3f4e52014-12-29 21:02:47 +00002556 for (const Action *A : C.getActions())
2557 if (A->getType() != types::TY_Nothing)
Daniel Dunbare75d8342009-03-16 06:56:51 +00002558 ++NumOutputs;
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00002559
Daniel Dunbare75d8342009-03-16 06:56:51 +00002560 if (NumOutputs > 1) {
2561 Diag(clang::diag::err_drv_output_argument_with_multiple_files);
Craig Topper92fc2df2014-05-17 16:56:41 +00002562 FinalOutput = nullptr;
Daniel Dunbare75d8342009-03-16 06:56:51 +00002563 }
2564 }
2565
Chad Rosier35767232013-04-30 22:01:21 +00002566 // Collect the list of architectures.
2567 llvm::StringSet<> ArchNames;
Saleem Abdulrasool688b6bc2014-12-29 19:01:36 +00002568 if (C.getDefaultToolChain().getTriple().isOSBinFormatMachO())
2569 for (const Arg *A : C.getArgs())
Chad Rosier35767232013-04-30 22:01:21 +00002570 if (A->getOption().matches(options::OPT_arch))
2571 ArchNames.insert(A->getValue());
Chad Rosier35767232013-04-30 22:01:21 +00002572
Justin Lebarb44f6fe2016-01-14 21:41:21 +00002573 // Set of (Action, canonical ToolChain triple) pairs we've built jobs for.
2574 std::map<std::pair<const Action *, std::string>, InputInfo> CachedResults;
Saleem Abdulrasool688b6bc2014-12-29 19:01:36 +00002575 for (Action *A : C.getActions()) {
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00002576 // If we are linking an image for multiple archs then the linker wants
2577 // -arch_multiple and -final_output <final image name>. Unfortunately, this
2578 // doesn't fit in cleanly because we have to pass this information down.
Daniel Dunbare75d8342009-03-16 06:56:51 +00002579 //
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00002580 // FIXME: This is a hack; find a cleaner way to integrate this into the
2581 // process.
Craig Topper92fc2df2014-05-17 16:56:41 +00002582 const char *LinkingOutput = nullptr;
Daniel Dunbardd765242009-03-26 16:12:09 +00002583 if (isa<LipoJobAction>(A)) {
Daniel Dunbare75d8342009-03-16 06:56:51 +00002584 if (FinalOutput)
Richard Smithbd55daf2012-11-01 04:30:05 +00002585 LinkingOutput = FinalOutput->getValue();
Daniel Dunbare75d8342009-03-16 06:56:51 +00002586 else
Hans Wennborga7707222015-01-09 17:38:53 +00002587 LinkingOutput = getDefaultImageName();
Daniel Dunbare75d8342009-03-16 06:56:51 +00002588 }
2589
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00002590 BuildJobsForAction(C, A, &C.getDefaultToolChain(),
Mehdi Aminic50b1a22016-10-07 21:27:26 +00002591 /*BoundArch*/ StringRef(),
Daniel Dunbare75d8342009-03-16 06:56:51 +00002592 /*AtTopLevel*/ true,
Chad Rosier35767232013-04-30 22:01:21 +00002593 /*MultipleArchs*/ ArchNames.size() > 1,
Samuel Antaod06239d2016-07-15 23:13:27 +00002594 /*LinkingOutput*/ LinkingOutput, CachedResults,
Samuel Antao3b7e38b2016-10-27 18:14:55 +00002595 /*TargetDeviceOffloadKind*/ Action::OFK_None);
Daniel Dunbare75d8342009-03-16 06:56:51 +00002596 }
Daniel Dunbar3ce436d2009-03-16 06:42:30 +00002597
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00002598 // If the user passed -Qunused-arguments or there were errors, don't warn
2599 // about any unused arguments.
Argyrios Kyrtzidis31448a42010-11-18 21:47:07 +00002600 if (Diags.hasErrorOccurred() ||
Daniel Dunbara3cfbe32009-04-07 19:04:18 +00002601 C.getArgs().hasArg(options::OPT_Qunused_arguments))
Daniel Dunbard175d972009-03-18 18:03:46 +00002602 return;
2603
Daniel Dunbar58399ae2009-03-29 22:24:54 +00002604 // Claim -### here.
Douglas Katzmana67e50c2015-06-26 15:47:46 +00002605 (void)C.getArgs().hasArg(options::OPT__HASH_HASH_HASH);
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00002606
Nico Weber47bf5052016-04-25 21:15:49 +00002607 // Claim --driver-mode, --rsp-quoting, it was handled earlier.
Douglas Katzmana67e50c2015-06-26 15:47:46 +00002608 (void)C.getArgs().hasArg(options::OPT_driver_mode);
Nico Weber47bf5052016-04-25 21:15:49 +00002609 (void)C.getArgs().hasArg(options::OPT_rsp_quoting);
Hans Wennborg70850d82013-07-18 20:29:38 +00002610
Saleem Abdulrasool688b6bc2014-12-29 19:01:36 +00002611 for (Arg *A : C.getArgs()) {
Daniel Dunbar3ce436d2009-03-16 06:42:30 +00002612 // FIXME: It would be nice to be able to send the argument to the
David Blaikie9c902b52011-09-25 23:23:43 +00002613 // DiagnosticsEngine, so that extra values, position, and so on could be
2614 // printed.
Daniel Dunbar90dd6f42009-04-04 00:52:26 +00002615 if (!A->isClaimed()) {
Michael J. Spencer66e2b202012-10-19 22:37:06 +00002616 if (A->getOption().hasFlag(options::NoArgumentUnused))
Daniel Dunbara3cfbe32009-04-07 19:04:18 +00002617 continue;
2618
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00002619 // Suppress the warning automatically if this is just a flag, and it is an
2620 // instance of an argument we already claimed.
Daniel Dunbar90dd6f42009-04-04 00:52:26 +00002621 const Option &Opt = A->getOption();
Michael J. Spencerad3ccc32012-08-20 21:41:17 +00002622 if (Opt.getKind() == Option::FlagClass) {
Daniel Dunbar90dd6f42009-04-04 00:52:26 +00002623 bool DuplicateClaimed = false;
2624
Sean Silva14facf32015-06-09 01:57:17 +00002625 for (const Arg *AA : C.getArgs().filtered(&Opt)) {
2626 if (AA->isClaimed()) {
Daniel Dunbar90dd6f42009-04-04 00:52:26 +00002627 DuplicateClaimed = true;
2628 break;
2629 }
2630 }
2631
2632 if (DuplicateClaimed)
2633 continue;
2634 }
2635
Ehsan Akhgarid8518332016-01-25 21:14:52 +00002636 // In clang-cl, don't mention unknown arguments here since they have
2637 // already been warned about.
2638 if (!IsCLMode() || !A->getOption().matches(options::OPT_UNKNOWN))
2639 Diag(clang::diag::warn_drv_unused_argument)
2640 << A->getAsString(C.getArgs());
Daniel Dunbar90dd6f42009-04-04 00:52:26 +00002641 }
Daniel Dunbar3ce436d2009-03-16 06:42:30 +00002642 }
Daniel Dunbar95e6b192009-03-13 22:12:33 +00002643}
Daniel Dunbarc4343942010-02-03 03:07:56 +00002644
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00002645namespace {
2646/// Utility class to control the collapse of dependent actions and select the
2647/// tools accordingly.
2648class ToolSelector final {
2649 /// The tool chain this selector refers to.
2650 const ToolChain &TC;
Daniel Dunbarf9ff3502010-05-14 02:03:00 +00002651
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00002652 /// The compilation this selector refers to.
2653 const Compilation &C;
Samuel Antaod06239d2016-07-15 23:13:27 +00002654
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00002655 /// The base action this selector refers to.
2656 const JobAction *BaseAction;
Samuel Antaod06239d2016-07-15 23:13:27 +00002657
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00002658 /// Set to true if the current toolchain refers to host actions.
2659 bool IsHostSelector;
Samuel Antaod06239d2016-07-15 23:13:27 +00002660
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00002661 /// Set to true if save-temps and embed-bitcode functionalities are active.
2662 bool SaveTemps;
2663 bool EmbedBitcode;
2664
2665 /// Get previous dependent action or null if that does not exist. If
2666 /// \a CanBeCollapsed is false, that action must be legal to collapse or
2667 /// null will be returned.
2668 const JobAction *getPrevDependentAction(const ActionList &Inputs,
2669 ActionList &SavedOffloadAction,
2670 bool CanBeCollapsed = true) {
2671 // An option can be collapsed only if it has a single input.
2672 if (Inputs.size() != 1)
Craig Topper92fc2df2014-05-17 16:56:41 +00002673 return nullptr;
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00002674
2675 Action *CurAction = *Inputs.begin();
2676 if (CanBeCollapsed &&
2677 !CurAction->isCollapsingWithNextDependentActionLegal())
2678 return nullptr;
2679
2680 // If the input action is an offload action. Look through it and save any
2681 // offload action that can be dropped in the event of a collapse.
2682 if (auto *OA = dyn_cast<OffloadAction>(CurAction)) {
2683 // If the dependent action is a device action, we will attempt to collapse
2684 // only with other device actions. Otherwise, we would do the same but
2685 // with host actions only.
2686 if (!IsHostSelector) {
2687 if (OA->hasSingleDeviceDependence(/*DoNotConsiderHostActions=*/true)) {
2688 CurAction =
2689 OA->getSingleDeviceDependence(/*DoNotConsiderHostActions=*/true);
2690 if (CanBeCollapsed &&
2691 !CurAction->isCollapsingWithNextDependentActionLegal())
2692 return nullptr;
2693 SavedOffloadAction.push_back(OA);
2694 return dyn_cast<JobAction>(CurAction);
2695 }
2696 } else if (OA->hasHostDependence()) {
2697 CurAction = OA->getHostDependence();
2698 if (CanBeCollapsed &&
2699 !CurAction->isCollapsingWithNextDependentActionLegal())
2700 return nullptr;
2701 SavedOffloadAction.push_back(OA);
2702 return dyn_cast<JobAction>(CurAction);
2703 }
2704 return nullptr;
2705 }
2706
2707 return dyn_cast<JobAction>(CurAction);
2708 }
2709
2710 /// Return true if an assemble action can be collapsed.
2711 bool canCollapseAssembleAction() const {
2712 return TC.useIntegratedAs() && !SaveTemps &&
2713 !C.getArgs().hasArg(options::OPT_via_file_asm) &&
2714 !C.getArgs().hasArg(options::OPT__SLASH_FA) &&
2715 !C.getArgs().hasArg(options::OPT__SLASH_Fa);
2716 }
2717
2718 /// Return true if a preprocessor action can be collapsed.
2719 bool canCollapsePreprocessorAction() const {
2720 return !C.getArgs().hasArg(options::OPT_no_integrated_cpp) &&
2721 !C.getArgs().hasArg(options::OPT_traditional_cpp) && !SaveTemps &&
2722 !C.getArgs().hasArg(options::OPT_rewrite_objc);
2723 }
2724
2725 /// Struct that relates an action with the offload actions that would be
2726 /// collapsed with it.
2727 struct JobActionInfo final {
2728 /// The action this info refers to.
2729 const JobAction *JA = nullptr;
2730 /// The offload actions we need to take care off if this action is
2731 /// collapsed.
2732 ActionList SavedOffloadAction;
2733 };
2734
2735 /// Append collapsed offload actions from the give nnumber of elements in the
2736 /// action info array.
2737 static void AppendCollapsedOffloadAction(ActionList &CollapsedOffloadAction,
2738 ArrayRef<JobActionInfo> &ActionInfo,
2739 unsigned ElementNum) {
2740 assert(ElementNum <= ActionInfo.size() && "Invalid number of elements.");
2741 for (unsigned I = 0; I < ElementNum; ++I)
2742 CollapsedOffloadAction.append(ActionInfo[I].SavedOffloadAction.begin(),
2743 ActionInfo[I].SavedOffloadAction.end());
2744 }
2745
2746 /// Functions that attempt to perform the combining. They detect if that is
2747 /// legal, and if so they update the inputs \a Inputs and the offload action
2748 /// that were collapsed in \a CollapsedOffloadAction. A tool that deals with
2749 /// the combined action is returned. If the combining is not legal or if the
2750 /// tool does not exist, null is returned.
2751 /// Currently three kinds of collapsing are supported:
2752 /// - Assemble + Backend + Compile;
2753 /// - Assemble + Backend ;
2754 /// - Backend + Compile.
2755 const Tool *
2756 combineAssembleBackendCompile(ArrayRef<JobActionInfo> ActionInfo,
2757 const ActionList *&Inputs,
2758 ActionList &CollapsedOffloadAction) {
2759 if (ActionInfo.size() < 3 || !canCollapseAssembleAction())
2760 return nullptr;
2761 auto *AJ = dyn_cast<AssembleJobAction>(ActionInfo[0].JA);
2762 auto *BJ = dyn_cast<BackendJobAction>(ActionInfo[1].JA);
2763 auto *CJ = dyn_cast<CompileJobAction>(ActionInfo[2].JA);
2764 if (!AJ || !BJ || !CJ)
2765 return nullptr;
2766
2767 // Get compiler tool.
2768 const Tool *T = TC.SelectTool(*CJ);
2769 if (!T)
2770 return nullptr;
2771
Steven Wu574b0f22016-03-01 01:07:58 +00002772 // When using -fembed-bitcode, it is required to have the same tool (clang)
2773 // for both CompilerJA and BackendJA. Otherwise, combine two stages.
2774 if (EmbedBitcode) {
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00002775 const Tool *BT = TC.SelectTool(*BJ);
2776 if (BT == T)
2777 return nullptr;
Steven Wu574b0f22016-03-01 01:07:58 +00002778 }
Bob Wilson23a55f12014-12-21 07:00:00 +00002779
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00002780 if (!T->hasIntegratedAssembler())
Bob Wilson23a55f12014-12-21 07:00:00 +00002781 return nullptr;
Samuel Antaod06239d2016-07-15 23:13:27 +00002782
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00002783 Inputs = &CJ->getInputs();
2784 AppendCollapsedOffloadAction(CollapsedOffloadAction, ActionInfo,
2785 /*NumElements=*/3);
2786 return T;
2787 }
2788 const Tool *combineAssembleBackend(ArrayRef<JobActionInfo> ActionInfo,
2789 const ActionList *&Inputs,
2790 ActionList &CollapsedOffloadAction) {
2791 if (ActionInfo.size() < 2 || !canCollapseAssembleAction())
2792 return nullptr;
2793 auto *AJ = dyn_cast<AssembleJobAction>(ActionInfo[0].JA);
2794 auto *BJ = dyn_cast<BackendJobAction>(ActionInfo[1].JA);
2795 if (!AJ || !BJ)
2796 return nullptr;
2797
2798 // Retrieve the compile job, backend action must always be preceded by one.
2799 ActionList CompileJobOffloadActions;
2800 auto *CJ = getPrevDependentAction(BJ->getInputs(), CompileJobOffloadActions,
2801 /*CanBeCollapsed=*/false);
2802 if (!AJ || !BJ || !CJ)
2803 return nullptr;
2804
2805 assert(isa<CompileJobAction>(CJ) &&
2806 "Expecting compile job preceding backend job.");
2807
2808 // Get compiler tool.
2809 const Tool *T = TC.SelectTool(*CJ);
2810 if (!T)
2811 return nullptr;
2812
2813 if (!T->hasIntegratedAssembler())
2814 return nullptr;
2815
2816 Inputs = &BJ->getInputs();
2817 AppendCollapsedOffloadAction(CollapsedOffloadAction, ActionInfo,
2818 /*NumElements=*/2);
2819 return T;
2820 }
2821 const Tool *combineBackendCompile(ArrayRef<JobActionInfo> ActionInfo,
2822 const ActionList *&Inputs,
2823 ActionList &CollapsedOffloadAction) {
2824 if (ActionInfo.size() < 2 || !canCollapsePreprocessorAction())
2825 return nullptr;
2826 auto *BJ = dyn_cast<BackendJobAction>(ActionInfo[0].JA);
2827 auto *CJ = dyn_cast<CompileJobAction>(ActionInfo[1].JA);
2828 if (!BJ || !CJ)
2829 return nullptr;
2830
2831 // Get compiler tool.
2832 const Tool *T = TC.SelectTool(*CJ);
2833 if (!T)
2834 return nullptr;
2835
2836 if (T->canEmitIR() && (SaveTemps || EmbedBitcode))
2837 return nullptr;
2838
2839 Inputs = &CJ->getInputs();
2840 AppendCollapsedOffloadAction(CollapsedOffloadAction, ActionInfo,
2841 /*NumElements=*/2);
2842 return T;
2843 }
2844
2845 /// Updates the inputs if the obtained tool supports combining with
2846 /// preprocessor action, and the current input is indeed a preprocessor
2847 /// action. If combining results in the collapse of offloading actions, those
2848 /// are appended to \a CollapsedOffloadAction.
2849 void combineWithPreprocessor(const Tool *T, const ActionList *&Inputs,
2850 ActionList &CollapsedOffloadAction) {
2851 if (!T || !canCollapsePreprocessorAction() || !T->hasIntegratedCPP())
2852 return;
2853
2854 // Attempt to get a preprocessor action dependence.
2855 ActionList PreprocessJobOffloadActions;
2856 auto *PJ = getPrevDependentAction(*Inputs, PreprocessJobOffloadActions);
2857 if (!PJ || !isa<PreprocessJobAction>(PJ))
2858 return;
2859
2860 // This is legal to combine. Append any offload action we found and set the
2861 // current inputs to preprocessor inputs.
2862 CollapsedOffloadAction.append(PreprocessJobOffloadActions.begin(),
2863 PreprocessJobOffloadActions.end());
2864 Inputs = &PJ->getInputs();
2865 }
2866
2867public:
2868 ToolSelector(const JobAction *BaseAction, const ToolChain &TC,
2869 const Compilation &C, bool SaveTemps, bool EmbedBitcode)
2870 : TC(TC), C(C), BaseAction(BaseAction), SaveTemps(SaveTemps),
2871 EmbedBitcode(EmbedBitcode) {
2872 assert(BaseAction && "Invalid base action.");
2873 IsHostSelector = BaseAction->getOffloadingDeviceKind() == Action::OFK_None;
2874 }
2875
2876 /// Check if a chain of actions can be combined and return the tool that can
2877 /// handle the combination of actions. The pointer to the current inputs \a
2878 /// Inputs and the list of offload actions \a CollapsedOffloadActions
2879 /// connected to collapsed actions are updated accordingly. The latter enables
2880 /// the caller of the selector to process them afterwards instead of just
2881 /// dropping them. If no suitable tool is found, null will be returned.
2882 const Tool *getTool(const ActionList *&Inputs,
2883 ActionList &CollapsedOffloadAction) {
2884 //
2885 // Get the largest chain of actions that we could combine.
2886 //
2887
2888 SmallVector<JobActionInfo, 5> ActionChain(1);
2889 ActionChain.back().JA = BaseAction;
2890 while (ActionChain.back().JA) {
2891 const Action *CurAction = ActionChain.back().JA;
2892
2893 // Grow the chain by one element.
2894 ActionChain.resize(ActionChain.size() + 1);
2895 JobActionInfo &AI = ActionChain.back();
2896
2897 // Attempt to fill it with the
2898 AI.JA =
2899 getPrevDependentAction(CurAction->getInputs(), AI.SavedOffloadAction);
Daniel Dunbarc4343942010-02-03 03:07:56 +00002900 }
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00002901
2902 // Pop the last action info as it could not be filled.
2903 ActionChain.pop_back();
2904
2905 //
2906 // Attempt to combine actions. If all combining attempts failed, just return
2907 // the tool of the provided action. At the end we attempt to combine the
2908 // action with any preprocessor action it may depend on.
2909 //
2910
2911 const Tool *T = combineAssembleBackendCompile(ActionChain, Inputs,
2912 CollapsedOffloadAction);
2913 if (!T)
2914 T = combineAssembleBackend(ActionChain, Inputs, CollapsedOffloadAction);
2915 if (!T)
2916 T = combineBackendCompile(ActionChain, Inputs, CollapsedOffloadAction);
2917 if (!T) {
2918 Inputs = &BaseAction->getInputs();
2919 T = TC.SelectTool(*BaseAction);
2920 }
2921
2922 combineWithPreprocessor(T, Inputs, CollapsedOffloadAction);
2923 return T;
Daniel Dunbarc4343942010-02-03 03:07:56 +00002924 }
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00002925};
Daniel Dunbarc4343942010-02-03 03:07:56 +00002926}
2927
Samuel Antao3b7e38b2016-10-27 18:14:55 +00002928/// Return a string that uniquely identifies the result of a job. The bound arch
2929/// is not necessarily represented in the toolchain's triple -- for example,
2930/// armv7 and armv7s both map to the same triple -- so we need both in our map.
2931/// Also, we need to add the offloading device kind, as the same tool chain can
2932/// be used for host and device for some programming models, e.g. OpenMP.
2933static std::string GetTriplePlusArchString(const ToolChain *TC,
2934 StringRef BoundArch,
2935 Action::OffloadKind OffloadKind) {
Justin Lebar55c83322016-01-16 03:30:08 +00002936 std::string TriplePlusArch = TC->getTriple().normalize();
Mehdi Aminic50b1a22016-10-07 21:27:26 +00002937 if (!BoundArch.empty()) {
Justin Lebar55c83322016-01-16 03:30:08 +00002938 TriplePlusArch += "-";
2939 TriplePlusArch += BoundArch;
2940 }
Samuel Antao59efaed2016-10-27 17:31:22 +00002941 TriplePlusArch += "-";
Samuel Antao3b7e38b2016-10-27 18:14:55 +00002942 TriplePlusArch += Action::GetOffloadKindName(OffloadKind);
2943 return TriplePlusArch;
2944}
2945
2946InputInfo Driver::BuildJobsForAction(
2947 Compilation &C, const Action *A, const ToolChain *TC, StringRef BoundArch,
2948 bool AtTopLevel, bool MultipleArchs, const char *LinkingOutput,
2949 std::map<std::pair<const Action *, std::string>, InputInfo> &CachedResults,
2950 Action::OffloadKind TargetDeviceOffloadKind) const {
2951 std::pair<const Action *, std::string> ActionTC = {
2952 A, GetTriplePlusArchString(TC, BoundArch, TargetDeviceOffloadKind)};
Justin Lebarb44f6fe2016-01-14 21:41:21 +00002953 auto CachedResult = CachedResults.find(ActionTC);
2954 if (CachedResult != CachedResults.end()) {
2955 return CachedResult->second;
2956 }
Samuel Antaod06239d2016-07-15 23:13:27 +00002957 InputInfo Result = BuildJobsForActionNoCache(
2958 C, A, TC, BoundArch, AtTopLevel, MultipleArchs, LinkingOutput,
Samuel Antao3b7e38b2016-10-27 18:14:55 +00002959 CachedResults, TargetDeviceOffloadKind);
Justin Lebarb44f6fe2016-01-14 21:41:21 +00002960 CachedResults[ActionTC] = Result;
2961 return Result;
2962}
2963
2964InputInfo Driver::BuildJobsForActionNoCache(
Mehdi Aminic50b1a22016-10-07 21:27:26 +00002965 Compilation &C, const Action *A, const ToolChain *TC, StringRef BoundArch,
Justin Lebarb44f6fe2016-01-14 21:41:21 +00002966 bool AtTopLevel, bool MultipleArchs, const char *LinkingOutput,
Samuel Antaod06239d2016-07-15 23:13:27 +00002967 std::map<std::pair<const Action *, std::string>, InputInfo> &CachedResults,
Samuel Antao3b7e38b2016-10-27 18:14:55 +00002968 Action::OffloadKind TargetDeviceOffloadKind) const {
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00002969 llvm::PrettyStackTraceString CrashInfo("Building compilation jobs");
Daniel Dunbarc4acf9d2009-03-18 23:18:19 +00002970
Samuel Antaod06239d2016-07-15 23:13:27 +00002971 InputInfoList OffloadDependencesInputInfo;
Samuel Antao3b7e38b2016-10-27 18:14:55 +00002972 bool BuildingForOffloadDevice = TargetDeviceOffloadKind != Action::OFK_None;
Samuel Antaod06239d2016-07-15 23:13:27 +00002973 if (const OffloadAction *OA = dyn_cast<OffloadAction>(A)) {
2974 // The offload action is expected to be used in four different situations.
2975 //
2976 // a) Set a toolchain/architecture/kind for a host action:
2977 // Host Action 1 -> OffloadAction -> Host Action 2
2978 //
2979 // b) Set a toolchain/architecture/kind for a device action;
2980 // Device Action 1 -> OffloadAction -> Device Action 2
2981 //
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00002982 // c) Specify a device dependence to a host action;
Samuel Antaod06239d2016-07-15 23:13:27 +00002983 // Device Action 1 _
2984 // \
2985 // Host Action 1 ---> OffloadAction -> Host Action 2
2986 //
2987 // d) Specify a host dependence to a device action.
2988 // Host Action 1 _
2989 // \
2990 // Device Action 1 ---> OffloadAction -> Device Action 2
2991 //
2992 // For a) and b), we just return the job generated for the dependence. For
2993 // c) and d) we override the current action with the host/device dependence
2994 // if the current toolchain is host/device and set the offload dependences
2995 // info with the jobs obtained from the device/host dependence(s).
2996
2997 // If there is a single device option, just generate the job for it.
2998 if (OA->hasSingleDeviceDependence()) {
2999 InputInfo DevA;
3000 OA->doOnEachDeviceDependence([&](Action *DepA, const ToolChain *DepTC,
3001 const char *DepBoundArch) {
3002 DevA =
3003 BuildJobsForAction(C, DepA, DepTC, DepBoundArch, AtTopLevel,
3004 /*MultipleArchs*/ !!DepBoundArch, LinkingOutput,
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003005 CachedResults, DepA->getOffloadingDeviceKind());
Samuel Antaod06239d2016-07-15 23:13:27 +00003006 });
3007 return DevA;
Artem Belevich0ff05cd2015-07-13 23:27:56 +00003008 }
Samuel Antaod06239d2016-07-15 23:13:27 +00003009
3010 // If 'Action 2' is host, we generate jobs for the device dependences and
3011 // override the current action with the host dependence. Otherwise, we
3012 // generate the host dependences and override the action with the device
3013 // dependence. The dependences can't therefore be a top-level action.
3014 OA->doOnEachDependence(
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003015 /*IsHostDependence=*/BuildingForOffloadDevice,
Samuel Antaod06239d2016-07-15 23:13:27 +00003016 [&](Action *DepA, const ToolChain *DepTC, const char *DepBoundArch) {
3017 OffloadDependencesInputInfo.push_back(BuildJobsForAction(
3018 C, DepA, DepTC, DepBoundArch, /*AtTopLevel=*/false,
3019 /*MultipleArchs*/ !!DepBoundArch, LinkingOutput, CachedResults,
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003020 DepA->getOffloadingDeviceKind()));
Samuel Antaod06239d2016-07-15 23:13:27 +00003021 });
3022
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003023 A = BuildingForOffloadDevice
Samuel Antaod06239d2016-07-15 23:13:27 +00003024 ? OA->getSingleDeviceDependence(/*DoNotConsiderHostActions=*/true)
3025 : OA->getHostDependence();
Artem Belevich0ff05cd2015-07-13 23:27:56 +00003026 }
3027
Daniel Dunbare75d8342009-03-16 06:56:51 +00003028 if (const InputAction *IA = dyn_cast<InputAction>(A)) {
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00003029 // FIXME: It would be nice to not claim this here; maybe the old scheme of
3030 // just using Args was better?
Daniel Dunbar5cdf3e02009-03-19 07:29:38 +00003031 const Arg &Input = IA->getInputArg();
3032 Input.claim();
Daniel Dunbar35cbfeb2010-06-09 22:31:08 +00003033 if (Input.getOption().matches(options::OPT_INPUT)) {
Richard Smithbd55daf2012-11-01 04:30:05 +00003034 const char *Name = Input.getValue();
Justin Lebard98cea82016-01-11 23:15:21 +00003035 return InputInfo(A, Name, /* BaseInput = */ Name);
Douglas Katzman678d0cb2015-06-16 18:01:24 +00003036 }
Justin Lebard98cea82016-01-11 23:15:21 +00003037 return InputInfo(A, &Input, /* BaseInput = */ "");
Daniel Dunbare75d8342009-03-16 06:56:51 +00003038 }
3039
3040 if (const BindArchAction *BAA = dyn_cast<BindArchAction>(A)) {
Chad Rosiera78a6eb2012-04-27 16:50:38 +00003041 const ToolChain *TC;
Mehdi Aminic50b1a22016-10-07 21:27:26 +00003042 StringRef ArchName = BAA->getArchName();
Daniel Dunbar1ef3f2a2009-09-08 23:37:19 +00003043
Mehdi Aminic50b1a22016-10-07 21:27:26 +00003044 if (!ArchName.empty())
Andrey Turetskiy6a8b91d2016-04-21 10:16:48 +00003045 TC = &getToolChain(C.getArgs(),
3046 computeTargetTriple(*this, DefaultTargetTriple,
3047 C.getArgs(), ArchName));
Chad Rosiera78a6eb2012-04-27 16:50:38 +00003048 else
3049 TC = &C.getDefaultToolChain();
Daniel Dunbar1ef3f2a2009-09-08 23:37:19 +00003050
Nico Weber5a459f82016-02-23 19:30:43 +00003051 return BuildJobsForAction(C, *BAA->input_begin(), TC, ArchName, AtTopLevel,
Samuel Antaod06239d2016-07-15 23:13:27 +00003052 MultipleArchs, LinkingOutput, CachedResults,
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003053 TargetDeviceOffloadKind);
Daniel Dunbare75d8342009-03-16 06:56:51 +00003054 }
3055
Artem Belevich0ff05cd2015-07-13 23:27:56 +00003056
Daniel Dunbare75d8342009-03-16 06:56:51 +00003057 const ActionList *Inputs = &A->getInputs();
Daniel Dunbarc4343942010-02-03 03:07:56 +00003058
3059 const JobAction *JA = cast<JobAction>(A);
Samuel Antaod06239d2016-07-15 23:13:27 +00003060 ActionList CollapsedOffloadActions;
3061
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00003062 ToolSelector TS(JA, *TC, C, isSaveTempsEnabled(), embedBitcodeEnabled());
3063 const Tool *T = TS.getTool(Inputs, CollapsedOffloadActions);
3064
Rafael Espindola79764462013-03-24 15:06:53 +00003065 if (!T)
Justin Lebar9eaa4892016-01-11 23:09:32 +00003066 return InputInfo();
Daniel Dunbare75d8342009-03-16 06:56:51 +00003067
Samuel Antaod06239d2016-07-15 23:13:27 +00003068 // If we've collapsed action list that contained OffloadAction we
3069 // need to build jobs for host/device-side inputs it may have held.
3070 for (const auto *OA : CollapsedOffloadActions)
3071 cast<OffloadAction>(OA)->doOnEachDependence(
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003072 /*IsHostDependence=*/BuildingForOffloadDevice,
Samuel Antaod06239d2016-07-15 23:13:27 +00003073 [&](Action *DepA, const ToolChain *DepTC, const char *DepBoundArch) {
3074 OffloadDependencesInputInfo.push_back(BuildJobsForAction(
Artem Belevichbee2f412016-08-22 18:50:34 +00003075 C, DepA, DepTC, DepBoundArch, /* AtTopLevel */ false,
Samuel Antaod06239d2016-07-15 23:13:27 +00003076 /*MultipleArchs=*/!!DepBoundArch, LinkingOutput, CachedResults,
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003077 DepA->getOffloadingDeviceKind()));
Samuel Antaod06239d2016-07-15 23:13:27 +00003078 });
Artem Belevichf8144ab2015-08-27 18:10:41 +00003079
Daniel Dunbare75d8342009-03-16 06:56:51 +00003080 // Only use pipes when there is exactly one input.
Daniel Dunbar1a093d22009-03-18 06:00:36 +00003081 InputInfoList InputInfos;
Saleem Abdulrasoolda3f4e52014-12-29 21:02:47 +00003082 for (const Action *Input : *Inputs) {
Eric Christopher14668dd2013-02-18 00:38:25 +00003083 // Treat dsymutil and verify sub-jobs as being at the top-level too, they
3084 // shouldn't get temporary output names.
Daniel Dunbar6beaf512010-06-04 18:28:41 +00003085 // FIXME: Clean this up.
Justin Lebar9eaa4892016-01-11 23:09:32 +00003086 bool SubJobAtTopLevel =
3087 AtTopLevel && (isa<DsymutilJobAction>(A) || isa<VerifyJobAction>(A));
Samuel Antaod06239d2016-07-15 23:13:27 +00003088 InputInfos.push_back(BuildJobsForAction(
3089 C, Input, TC, BoundArch, SubJobAtTopLevel, MultipleArchs, LinkingOutput,
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003090 CachedResults, A->getOffloadingDeviceKind()));
Daniel Dunbare75d8342009-03-16 06:56:51 +00003091 }
3092
Daniel Dunbare75d8342009-03-16 06:56:51 +00003093 // Always use the first input as the base input.
3094 const char *BaseInput = InputInfos[0].getBaseInput();
Daniel Dunbar7a178a42009-03-17 17:53:55 +00003095
Daniel Dunbar6beaf512010-06-04 18:28:41 +00003096 // ... except dsymutil actions, which use their actual input as the base
3097 // input.
3098 if (JA->getType() == types::TY_dSYM)
3099 BaseInput = InputInfos[0].getFilename();
3100
Samuel Antaod06239d2016-07-15 23:13:27 +00003101 // Append outputs of offload device jobs to the input list
3102 if (!OffloadDependencesInputInfo.empty())
3103 InputInfos.append(OffloadDependencesInputInfo.begin(),
3104 OffloadDependencesInputInfo.end());
Artem Belevich0ff05cd2015-07-13 23:27:56 +00003105
Vedant Kumar18286cf2016-07-27 23:02:20 +00003106 // Set the effective triple of the toolchain for the duration of this job.
3107 llvm::Triple EffectiveTriple;
3108 const ToolChain &ToolTC = T->getToolChain();
Samuel Antao31fef982016-10-27 17:39:44 +00003109 const ArgList &Args =
3110 C.getArgsForToolChain(TC, BoundArch, A->getOffloadingDeviceKind());
Vedant Kumar18286cf2016-07-27 23:02:20 +00003111 if (InputInfos.size() != 1) {
3112 EffectiveTriple = llvm::Triple(ToolTC.ComputeEffectiveClangTriple(Args));
3113 } else {
3114 // Pass along the input type if it can be unambiguously determined.
3115 EffectiveTriple = llvm::Triple(
3116 ToolTC.ComputeEffectiveClangTriple(Args, InputInfos[0].getType()));
3117 }
3118 RegisterEffectiveTriple TripleRAII(ToolTC, EffectiveTriple);
3119
Daniel Dunbard00272f2010-08-02 02:38:15 +00003120 // Determine the place to write output to, if any.
Justin Lebar9eaa4892016-01-11 23:09:32 +00003121 InputInfo Result;
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003122 InputInfoList UnbundlingResults;
3123 if (auto *UA = dyn_cast<OffloadUnbundlingJobAction>(JA)) {
3124 // If we have an unbundling job, we need to create results for all the
3125 // outputs. We also update the results cache so that other actions using
3126 // this unbundling action can get the right results.
3127 for (auto &UI : UA->getDependentActionsInfo()) {
3128 assert(UI.DependentOffloadKind != Action::OFK_None &&
3129 "Unbundling with no offloading??");
3130
3131 // Unbundling actions are never at the top level. When we generate the
3132 // offloading prefix, we also do that for the host file because the
3133 // unbundling action does not change the type of the output which can
3134 // cause a overwrite.
3135 std::string OffloadingPrefix = Action::GetOffloadingFileNamePrefix(
3136 UI.DependentOffloadKind,
3137 UI.DependentToolChain->getTriple().normalize(),
3138 /*CreatePrefixForHost=*/true);
3139 auto CurI = InputInfo(
3140 UA, GetNamedOutputPath(C, *UA, BaseInput, UI.DependentBoundArch,
3141 /*AtTopLevel=*/false, MultipleArchs,
3142 OffloadingPrefix),
3143 BaseInput);
3144 // Save the unbundling result.
3145 UnbundlingResults.push_back(CurI);
3146
3147 // Get the unique string identifier for this dependence and cache the
3148 // result.
3149 CachedResults[{A, GetTriplePlusArchString(
3150 UI.DependentToolChain, UI.DependentBoundArch,
3151 UI.DependentOffloadKind)}] = CurI;
3152 }
3153
3154 // Now that we have all the results generated, select the one that should be
3155 // returned for the current depending action.
3156 std::pair<const Action *, std::string> ActionTC = {
3157 A, GetTriplePlusArchString(TC, BoundArch, TargetDeviceOffloadKind)};
3158 assert(CachedResults.find(ActionTC) != CachedResults.end() &&
3159 "Result does not exist??");
3160 Result = CachedResults[ActionTC];
3161 } else if (JA->getType() == types::TY_Nothing)
Justin Lebard98cea82016-01-11 23:15:21 +00003162 Result = InputInfo(A, BaseInput);
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003163 else {
3164 // We only have to generate a prefix for the host if this is not a top-level
3165 // action.
3166 std::string OffloadingPrefix = Action::GetOffloadingFileNamePrefix(
3167 A->getOffloadingDeviceKind(), TC->getTriple().normalize(),
3168 /*CreatePrefixForHost=*/!!A->getOffloadingHostActiveKinds() &&
3169 !AtTopLevel);
Justin Lebard98cea82016-01-11 23:15:21 +00003170 Result = InputInfo(A, GetNamedOutputPath(C, *JA, BaseInput, BoundArch,
Samuel Antaod06239d2016-07-15 23:13:27 +00003171 AtTopLevel, MultipleArchs,
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003172 OffloadingPrefix),
Justin Lebard98cea82016-01-11 23:15:21 +00003173 BaseInput);
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003174 }
Daniel Dunbar7a178a42009-03-17 17:53:55 +00003175
Chad Rosierbe10f982011-08-02 17:58:04 +00003176 if (CCCPrintBindings && !CCGenDiagnostics) {
Rafael Espindola79764462013-03-24 15:06:53 +00003177 llvm::errs() << "# \"" << T->getToolChain().getTripleString() << '"'
3178 << " - \"" << T->getName() << "\", inputs: [";
Daniel Dunbarb39cc522009-03-17 22:47:06 +00003179 for (unsigned i = 0, e = InputInfos.size(); i != e; ++i) {
3180 llvm::errs() << InputInfos[i].getAsString();
3181 if (i + 1 != e)
3182 llvm::errs() << ", ";
3183 }
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003184 if (UnbundlingResults.empty())
3185 llvm::errs() << "], output: " << Result.getAsString() << "\n";
3186 else {
3187 llvm::errs() << "], outputs: [";
3188 for (unsigned i = 0, e = UnbundlingResults.size(); i != e; ++i) {
3189 llvm::errs() << UnbundlingResults[i].getAsString();
3190 if (i + 1 != e)
3191 llvm::errs() << ", ";
3192 }
3193 llvm::errs() << "] \n";
3194 }
Daniel Dunbarb39cc522009-03-17 22:47:06 +00003195 } else {
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003196 if (UnbundlingResults.empty())
3197 T->ConstructJob(
3198 C, *JA, Result, InputInfos,
3199 C.getArgsForToolChain(TC, BoundArch, JA->getOffloadingDeviceKind()),
3200 LinkingOutput);
3201 else
Samuel Antao7108bf32016-11-03 15:41:50 +00003202 T->ConstructJobMultipleOutputs(
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003203 C, *JA, UnbundlingResults, InputInfos,
3204 C.getArgsForToolChain(TC, BoundArch, JA->getOffloadingDeviceKind()),
3205 LinkingOutput);
Daniel Dunbarb39cc522009-03-17 22:47:06 +00003206 }
Justin Lebar9eaa4892016-01-11 23:09:32 +00003207 return Result;
Daniel Dunbare75d8342009-03-16 06:56:51 +00003208}
3209
Hans Wennborga7707222015-01-09 17:38:53 +00003210const char *Driver::getDefaultImageName() const {
3211 llvm::Triple Target(llvm::Triple::normalize(DefaultTargetTriple));
3212 return Target.isOSWindows() ? "a.exe" : "a.out";
3213}
3214
Hans Wennborg2c21f742013-10-17 16:16:23 +00003215/// \brief Create output filename based on ArgValue, which could either be a
3216/// full filename, filename without extension, or a directory. If ArgValue
3217/// does not provide a filename, then use BaseName, and use the extension
3218/// suitable for FileType.
Hans Wennborg207fcf02013-08-12 21:56:42 +00003219static const char *MakeCLOutputFilename(const ArgList &Args, StringRef ArgValue,
Douglas Katzmana67e50c2015-06-26 15:47:46 +00003220 StringRef BaseName,
3221 types::ID FileType) {
Hans Wennborg207fcf02013-08-12 21:56:42 +00003222 SmallString<128> Filename = ArgValue;
Justin Bogner5aaf2e72014-06-26 20:59:36 +00003223
Hans Wennborgf1a74252013-09-10 20:18:04 +00003224 if (ArgValue.empty()) {
3225 // If the argument is empty, output to BaseName in the current dir.
3226 Filename = BaseName;
3227 } else if (llvm::sys::path::is_separator(Filename.back())) {
Hans Wennborg207fcf02013-08-12 21:56:42 +00003228 // If the argument is a directory, output to BaseName in that dir.
3229 llvm::sys::path::append(Filename, BaseName);
3230 }
3231
3232 if (!llvm::sys::path::has_extension(ArgValue)) {
3233 // If the argument didn't provide an extension, then set it.
3234 const char *Extension = types::getTypeTempSuffix(FileType, true);
Hans Wennborgf1a74252013-09-10 20:18:04 +00003235
3236 if (FileType == types::TY_Image &&
3237 Args.hasArg(options::OPT__SLASH_LD, options::OPT__SLASH_LDd)) {
3238 // The output file is a dll.
3239 Extension = "dll";
3240 }
3241
Hans Wennborg207fcf02013-08-12 21:56:42 +00003242 llvm::sys::path::replace_extension(Filename, Extension);
3243 }
3244
3245 return Args.MakeArgString(Filename.c_str());
3246}
3247
Douglas Katzmana67e50c2015-06-26 15:47:46 +00003248const char *Driver::GetNamedOutputPath(Compilation &C, const JobAction &JA,
Daniel Dunbar7a178a42009-03-17 17:53:55 +00003249 const char *BaseInput,
Mehdi Aminic50b1a22016-10-07 21:27:26 +00003250 StringRef BoundArch, bool AtTopLevel,
Samuel Antaod06239d2016-07-15 23:13:27 +00003251 bool MultipleArchs,
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003252 StringRef OffloadingPrefix) const {
Daniel Dunbar2608c542009-03-18 01:38:48 +00003253 llvm::PrettyStackTraceString CrashInfo("Computing output path");
Daniel Dunbar7a178a42009-03-17 17:53:55 +00003254 // Output to a user requested destination?
Douglas Katzmana67e50c2015-06-26 15:47:46 +00003255 if (AtTopLevel && !isa<DsymutilJobAction>(JA) && !isa<VerifyJobAction>(JA)) {
Daniel Dunbar7a178a42009-03-17 17:53:55 +00003256 if (Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o))
Chad Rosier633dcdc2013-01-24 19:14:47 +00003257 return C.addResultFile(FinalOutput->getValue(), &JA);
Daniel Dunbar7a178a42009-03-17 17:53:55 +00003258 }
3259
Hans Wennborge0053472013-12-20 18:40:46 +00003260 // For /P, preprocess to file named after BaseInput.
3261 if (C.getArgs().hasArg(options::OPT__SLASH_P)) {
3262 assert(AtTopLevel && isa<PreprocessJobAction>(JA));
3263 StringRef BaseName = llvm::sys::path::filename(BaseInput);
Hans Wennborg04c764f2014-06-17 00:19:12 +00003264 StringRef NameArg;
Greg Bedwell065f70a2015-06-09 10:24:06 +00003265 if (Arg *A = C.getArgs().getLastArg(options::OPT__SLASH_Fi))
Hans Wennborg04c764f2014-06-17 00:19:12 +00003266 NameArg = A->getValue();
Douglas Katzmana67e50c2015-06-26 15:47:46 +00003267 return C.addResultFile(
3268 MakeCLOutputFilename(C.getArgs(), NameArg, BaseName, types::TY_PP_C),
3269 &JA);
Hans Wennborge0053472013-12-20 18:40:46 +00003270 }
3271
Nick Lewycky6e1ce292010-09-24 00:46:53 +00003272 // Default to writing to stdout?
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +00003273 if (AtTopLevel && !CCGenDiagnostics &&
3274 (isa<PreprocessJobAction>(JA) || JA.getType() == types::TY_ModuleFile))
Nick Lewycky6e1ce292010-09-24 00:46:53 +00003275 return "-";
3276
Hans Wennborg2c21f742013-10-17 16:16:23 +00003277 // Is this the assembly listing for /FA?
3278 if (JA.getType() == types::TY_PP_Asm &&
3279 (C.getArgs().hasArg(options::OPT__SLASH_FA) ||
3280 C.getArgs().hasArg(options::OPT__SLASH_Fa))) {
3281 // Use /Fa and the input filename to determine the asm file name.
3282 StringRef BaseName = llvm::sys::path::filename(BaseInput);
3283 StringRef FaValue = C.getArgs().getLastArgValue(options::OPT__SLASH_Fa);
Douglas Katzmana67e50c2015-06-26 15:47:46 +00003284 return C.addResultFile(
3285 MakeCLOutputFilename(C.getArgs(), FaValue, BaseName, JA.getType()),
3286 &JA);
Hans Wennborg2c21f742013-10-17 16:16:23 +00003287 }
3288
Daniel Dunbar7a178a42009-03-17 17:53:55 +00003289 // Output to a temporary file?
Reid Kleckner68eb60b2015-02-02 22:41:48 +00003290 if ((!AtTopLevel && !isSaveTempsEnabled() &&
Douglas Katzmana67e50c2015-06-26 15:47:46 +00003291 !C.getArgs().hasArg(options::OPT__SLASH_Fo)) ||
Chad Rosierbe10f982011-08-02 17:58:04 +00003292 CCGenDiagnostics) {
Chad Rosier97c37372011-08-26 22:27:02 +00003293 StringRef Name = llvm::sys::path::filename(BaseInput);
3294 std::pair<StringRef, StringRef> Split = Name.split('.');
Douglas Katzmana67e50c2015-06-26 15:47:46 +00003295 std::string TmpName = GetTemporaryPath(
3296 Split.first, types::getTypeTempSuffix(JA.getType(), IsCLMode()));
Malcolm Parsonsf76f6502016-11-02 10:39:27 +00003297 return C.addTempFile(C.getArgs().MakeArgString(TmpName));
Daniel Dunbar7a178a42009-03-17 17:53:55 +00003298 }
3299
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00003300 SmallString<128> BasePath(BaseInput);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003301 StringRef BaseName;
Daniel Dunbar67fea712011-03-25 18:16:51 +00003302
3303 // Dsymutil actions should use the full path.
Eric Christopher551ef452011-08-23 17:56:55 +00003304 if (isa<DsymutilJobAction>(JA) || isa<VerifyJobAction>(JA))
Daniel Dunbar67fea712011-03-25 18:16:51 +00003305 BaseName = BasePath;
3306 else
3307 BaseName = llvm::sys::path::filename(BasePath);
Daniel Dunbar7a178a42009-03-17 17:53:55 +00003308
3309 // Determine what the derived output name should be.
3310 const char *NamedOutput;
Hans Wennborg2b89a262013-08-06 22:11:28 +00003311
Hans Wennborg625fba82016-10-04 21:01:04 +00003312 if ((JA.getType() == types::TY_Object || JA.getType() == types::TY_LTO_BC) &&
Ehsan Akhgari81f36b72014-09-11 18:16:21 +00003313 C.getArgs().hasArg(options::OPT__SLASH_Fo, options::OPT__SLASH_o)) {
3314 // The /Fo or /o flag decides the object filename.
Douglas Katzmana67e50c2015-06-26 15:47:46 +00003315 StringRef Val =
3316 C.getArgs()
3317 .getLastArg(options::OPT__SLASH_Fo, options::OPT__SLASH_o)
3318 ->getValue();
3319 NamedOutput =
3320 MakeCLOutputFilename(C.getArgs(), Val, BaseName, types::TY_Object);
Hans Wennborg207fcf02013-08-12 21:56:42 +00003321 } else if (JA.getType() == types::TY_Image &&
Douglas Katzmana67e50c2015-06-26 15:47:46 +00003322 C.getArgs().hasArg(options::OPT__SLASH_Fe,
3323 options::OPT__SLASH_o)) {
Ehsan Akhgari81f36b72014-09-11 18:16:21 +00003324 // The /Fe or /o flag names the linked file.
Douglas Katzmana67e50c2015-06-26 15:47:46 +00003325 StringRef Val =
3326 C.getArgs()
3327 .getLastArg(options::OPT__SLASH_Fe, options::OPT__SLASH_o)
3328 ->getValue();
3329 NamedOutput =
3330 MakeCLOutputFilename(C.getArgs(), Val, BaseName, types::TY_Image);
Hans Wennborgf1a74252013-09-10 20:18:04 +00003331 } else if (JA.getType() == types::TY_Image) {
Hans Wennborg207fcf02013-08-12 21:56:42 +00003332 if (IsCLMode()) {
3333 // clang-cl uses BaseName for the executable name.
Douglas Katzmana67e50c2015-06-26 15:47:46 +00003334 NamedOutput =
3335 MakeCLOutputFilename(C.getArgs(), "", BaseName, types::TY_Image);
Samuel Antao59efaed2016-10-27 17:31:22 +00003336 } else {
Hans Wennborga7707222015-01-09 17:38:53 +00003337 SmallString<128> Output(getDefaultImageName());
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003338 Output += OffloadingPrefix;
Samuel Antao59efaed2016-10-27 17:31:22 +00003339 if (MultipleArchs && !BoundArch.empty()) {
3340 Output += "-";
3341 Output.append(BoundArch);
3342 }
Chad Rosier35767232013-04-30 22:01:21 +00003343 NamedOutput = C.getArgs().MakeArgString(Output.c_str());
Nico Weber2ca4be92016-03-01 23:16:44 +00003344 }
3345 } else if (JA.getType() == types::TY_PCH && IsCLMode()) {
Malcolm Parsonsf76f6502016-11-02 10:39:27 +00003346 NamedOutput = C.getArgs().MakeArgString(GetClPchPath(C, BaseName));
Daniel Dunbar7a178a42009-03-17 17:53:55 +00003347 } else {
Hans Wennborg0a096a02013-09-05 17:05:56 +00003348 const char *Suffix = types::getTypeTempSuffix(JA.getType(), IsCLMode());
Daniel Dunbar7a178a42009-03-17 17:53:55 +00003349 assert(Suffix && "All types used for output should have a suffix.");
3350
3351 std::string::size_type End = std::string::npos;
3352 if (!types::appendSuffixForType(JA.getType()))
3353 End = BaseName.rfind('.');
Chad Rosier35767232013-04-30 22:01:21 +00003354 SmallString<128> Suffixed(BaseName.substr(0, End));
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003355 Suffixed += OffloadingPrefix;
Mehdi Aminic50b1a22016-10-07 21:27:26 +00003356 if (MultipleArchs && !BoundArch.empty()) {
Chad Rosier35767232013-04-30 22:01:21 +00003357 Suffixed += "-";
3358 Suffixed.append(BoundArch);
3359 }
Bob Wilson23a55f12014-12-21 07:00:00 +00003360 // When using both -save-temps and -emit-llvm, use a ".tmp.bc" suffix for
3361 // the unoptimized bitcode so that it does not get overwritten by the ".bc"
3362 // optimized bitcode output.
3363 if (!AtTopLevel && C.getArgs().hasArg(options::OPT_emit_llvm) &&
3364 JA.getType() == types::TY_LLVM_BC)
3365 Suffixed += ".tmp";
Daniel Dunbar7a178a42009-03-17 17:53:55 +00003366 Suffixed += '.';
3367 Suffixed += Suffix;
3368 NamedOutput = C.getArgs().MakeArgString(Suffixed.c_str());
3369 }
3370
Reid Kleckner68eb60b2015-02-02 22:41:48 +00003371 // Prepend object file path if -save-temps=obj
3372 if (!AtTopLevel && isSaveTempsObj() && C.getArgs().hasArg(options::OPT_o) &&
3373 JA.getType() != types::TY_PCH) {
3374 Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o);
3375 SmallString<128> TempPath(FinalOutput->getValue());
3376 llvm::sys::path::remove_filename(TempPath);
3377 StringRef OutputFileName = llvm::sys::path::filename(NamedOutput);
3378 llvm::sys::path::append(TempPath, OutputFileName);
3379 NamedOutput = C.getArgs().MakeArgString(TempPath.c_str());
3380 }
3381
Chad Rosier62135492012-07-09 17:31:28 +00003382 // If we're saving temps and the temp file conflicts with the input file,
Chad Rosier5b58af02012-04-20 20:05:08 +00003383 // then avoid overwriting input file.
Reid Kleckner68eb60b2015-02-02 22:41:48 +00003384 if (!AtTopLevel && isSaveTempsEnabled() && NamedOutput == BaseName) {
Chad Rosier5b58af02012-04-20 20:05:08 +00003385 bool SameFile = false;
3386 SmallString<256> Result;
3387 llvm::sys::fs::current_path(Result);
3388 llvm::sys::path::append(Result, BaseName);
3389 llvm::sys::fs::equivalent(BaseInput, Result.c_str(), SameFile);
3390 // Must share the same path to conflict.
3391 if (SameFile) {
3392 StringRef Name = llvm::sys::path::filename(BaseInput);
3393 std::pair<StringRef, StringRef> Split = Name.split('.');
Douglas Katzmana67e50c2015-06-26 15:47:46 +00003394 std::string TmpName = GetTemporaryPath(
3395 Split.first, types::getTypeTempSuffix(JA.getType(), IsCLMode()));
Malcolm Parsonsf76f6502016-11-02 10:39:27 +00003396 return C.addTempFile(C.getArgs().MakeArgString(TmpName));
Chad Rosier5b58af02012-04-20 20:05:08 +00003397 }
Chad Rosierf8412cd2011-07-15 21:54:29 +00003398 }
3399
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00003400 // As an annoying special case, PCH generation doesn't strip the pathname.
Nico Weber8ab92192016-03-02 23:29:29 +00003401 if (JA.getType() == types::TY_PCH && !IsCLMode()) {
Michael J. Spencere1696752010-12-18 00:19:12 +00003402 llvm::sys::path::remove_filename(BasePath);
3403 if (BasePath.empty())
Daniel Dunbare6c83192009-03-18 09:58:30 +00003404 BasePath = NamedOutput;
3405 else
Michael J. Spencere1696752010-12-18 00:19:12 +00003406 llvm::sys::path::append(BasePath, NamedOutput);
Chad Rosier633dcdc2013-01-24 19:14:47 +00003407 return C.addResultFile(C.getArgs().MakeArgString(BasePath.c_str()), &JA);
Daniel Dunbar7a178a42009-03-17 17:53:55 +00003408 } else {
Chad Rosier633dcdc2013-01-24 19:14:47 +00003409 return C.addResultFile(NamedOutput, &JA);
Daniel Dunbar7a178a42009-03-17 17:53:55 +00003410 }
3411}
3412
Mehdi Amini12011172016-10-06 05:11:48 +00003413std::string Driver::GetFilePath(StringRef Name, const ToolChain &TC) const {
Chandler Carruth84559242010-03-22 01:52:07 +00003414 // Respect a limited subset of the '-Bprefix' functionality in GCC by
Logan Chiencd679fd2012-10-04 08:08:56 +00003415 // attempting to use this prefix when looking for file paths.
Douglas Katzman26eabf62015-06-24 15:10:30 +00003416 for (const std::string &Dir : PrefixDirs) {
Joerg Sonnenberger6165ab12011-03-21 13:51:29 +00003417 if (Dir.empty())
3418 continue;
Douglas Katzman26eabf62015-06-24 15:10:30 +00003419 SmallString<128> P(Dir[0] == '=' ? SysRoot + Dir.substr(1) : Dir);
Rafael Espindola609a6642013-06-24 18:33:43 +00003420 llvm::sys::path::append(P, Name);
3421 if (llvm::sys::fs::exists(Twine(P)))
Chandler Carruth84559242010-03-22 01:52:07 +00003422 return P.str();
3423 }
3424
Rafael Espindola609a6642013-06-24 18:33:43 +00003425 SmallString<128> P(ResourceDir);
3426 llvm::sys::path::append(P, Name);
3427 if (llvm::sys::fs::exists(Twine(P)))
Peter Collingbournefa9771f2011-09-06 02:08:31 +00003428 return P.str();
3429
Douglas Katzman26eabf62015-06-24 15:10:30 +00003430 for (const std::string &Dir : TC.getFilePaths()) {
Joerg Sonnenberger6165ab12011-03-21 13:51:29 +00003431 if (Dir.empty())
3432 continue;
Douglas Katzman26eabf62015-06-24 15:10:30 +00003433 SmallString<128> P(Dir[0] == '=' ? SysRoot + Dir.substr(1) : Dir);
Rafael Espindola609a6642013-06-24 18:33:43 +00003434 llvm::sys::path::append(P, Name);
3435 if (llvm::sys::fs::exists(Twine(P)))
Daniel Dunbar1ce81532009-09-09 22:33:00 +00003436 return P.str();
Daniel Dunbar68b01a02009-03-18 20:26:19 +00003437 }
3438
Daniel Dunbar1ce81532009-09-09 22:33:00 +00003439 return Name;
Daniel Dunbar5e0f6af2009-03-13 00:51:18 +00003440}
3441
Douglas Katzmana67e50c2015-06-26 15:47:46 +00003442void Driver::generatePrefixedToolNames(
Mehdi Amini12011172016-10-06 05:11:48 +00003443 StringRef Tool, const ToolChain &TC,
Douglas Katzmana67e50c2015-06-26 15:47:46 +00003444 SmallVectorImpl<std::string> &Names) const {
Saleem Abdulrasoolf0ba6ce2014-10-25 23:33:21 +00003445 // FIXME: Needs a better variable than DefaultTargetTriple
Mehdi Amini12011172016-10-06 05:11:48 +00003446 Names.emplace_back((DefaultTargetTriple + "-" + Tool).str());
Benjamin Kramer3204b152015-05-29 19:42:19 +00003447 Names.emplace_back(Tool);
Vasileios Kalintirisc744e122015-11-12 15:26:54 +00003448
3449 // Allow the discovery of tools prefixed with LLVM's default target triple.
3450 std::string LLVMDefaultTargetTriple = llvm::sys::getDefaultTargetTriple();
3451 if (LLVMDefaultTargetTriple != DefaultTargetTriple)
Mehdi Amini12011172016-10-06 05:11:48 +00003452 Names.emplace_back((LLVMDefaultTargetTriple + "-" + Tool).str());
Saleem Abdulrasoolf0ba6ce2014-10-25 23:33:21 +00003453}
3454
Benjamin Kramer7111b912014-11-04 20:26:01 +00003455static bool ScanDirForExecutable(SmallString<128> &Dir,
3456 ArrayRef<std::string> Names) {
Saleem Abdulrasoolf0ba6ce2014-10-25 23:33:21 +00003457 for (const auto &Name : Names) {
3458 llvm::sys::path::append(Dir, Name);
3459 if (llvm::sys::fs::can_execute(Twine(Dir)))
3460 return true;
3461 llvm::sys::path::remove_filename(Dir);
3462 }
3463 return false;
3464}
3465
Mehdi Amini12011172016-10-06 05:11:48 +00003466std::string Driver::GetProgramPath(StringRef Name, const ToolChain &TC) const {
Saleem Abdulrasoolf0ba6ce2014-10-25 23:33:21 +00003467 SmallVector<std::string, 2> TargetSpecificExecutables;
3468 generatePrefixedToolNames(Name, TC, TargetSpecificExecutables);
3469
Chandler Carruth84559242010-03-22 01:52:07 +00003470 // Respect a limited subset of the '-Bprefix' functionality in GCC by
Logan Chiencd679fd2012-10-04 08:08:56 +00003471 // attempting to use this prefix when looking for program paths.
Saleem Abdulrasool23d99b12014-09-16 03:48:32 +00003472 for (const auto &PrefixDir : PrefixDirs) {
3473 if (llvm::sys::fs::is_directory(PrefixDir)) {
3474 SmallString<128> P(PrefixDir);
Saleem Abdulrasoolf0ba6ce2014-10-25 23:33:21 +00003475 if (ScanDirForExecutable(P, TargetSpecificExecutables))
Rafael Espindola8be5c052013-06-19 13:24:29 +00003476 return P.str();
Simon Atanasyana47ba292012-10-31 14:39:28 +00003477 } else {
Mehdi Amini12011172016-10-06 05:11:48 +00003478 SmallString<128> P((PrefixDir + Name).str());
Rafael Espindola609a6642013-06-24 18:33:43 +00003479 if (llvm::sys::fs::can_execute(Twine(P)))
Rafael Espindola8be5c052013-06-19 13:24:29 +00003480 return P.str();
Simon Atanasyan86bdab72012-10-31 12:01:53 +00003481 }
Chandler Carruth84559242010-03-22 01:52:07 +00003482 }
3483
Daniel Dunbar68b01a02009-03-18 20:26:19 +00003484 const ToolChain::path_list &List = TC.getProgramPaths();
Saleem Abdulrasool23d99b12014-09-16 03:48:32 +00003485 for (const auto &Path : List) {
3486 SmallString<128> P(Path);
Saleem Abdulrasoolf0ba6ce2014-10-25 23:33:21 +00003487 if (ScanDirForExecutable(P, TargetSpecificExecutables))
Rafael Espindola8be5c052013-06-19 13:24:29 +00003488 return P.str();
Daniel Dunbar68b01a02009-03-18 20:26:19 +00003489 }
3490
Daniel Dunbar76ce7412009-03-23 16:15:50 +00003491 // If all else failed, search the path.
Michael J. Spencerb011d482014-11-07 21:30:32 +00003492 for (const auto &TargetSpecificExecutable : TargetSpecificExecutables)
3493 if (llvm::ErrorOr<std::string> P =
3494 llvm::sys::findProgramByName(TargetSpecificExecutable))
Michael J. Spencer04162ea2014-11-04 01:30:55 +00003495 return *P;
Daniel Dunbar6f668772009-03-18 21:34:08 +00003496
Daniel Dunbar1ce81532009-09-09 22:33:00 +00003497 return Name;
Daniel Dunbar5e0f6af2009-03-13 00:51:18 +00003498}
3499
Mehdi Amini12011172016-10-06 05:11:48 +00003500std::string Driver::GetTemporaryPath(StringRef Prefix, StringRef Suffix) const {
Rafael Espindola37d229d2013-06-25 04:26:55 +00003501 SmallString<128> Path;
Rafael Espindolac0809172014-06-12 14:02:15 +00003502 std::error_code EC = llvm::sys::fs::createTemporaryFile(Prefix, Suffix, Path);
Rafael Espindola37d229d2013-06-25 04:26:55 +00003503 if (EC) {
3504 Diag(clang::diag::err_unable_to_make_temp) << EC.message();
Daniel Dunbare627c1c2009-03-18 19:34:39 +00003505 return "";
3506 }
3507
Rafael Espindola37d229d2013-06-25 04:26:55 +00003508 return Path.str();
Daniel Dunbare627c1c2009-03-18 19:34:39 +00003509}
3510
Nico Weber2ca4be92016-03-01 23:16:44 +00003511std::string Driver::GetClPchPath(Compilation &C, StringRef BaseName) const {
3512 SmallString<128> Output;
3513 if (Arg *FpArg = C.getArgs().getLastArg(options::OPT__SLASH_Fp)) {
3514 // FIXME: If anybody needs it, implement this obscure rule:
3515 // "If you specify a directory without a file name, the default file name
3516 // is VCx0.pch., where x is the major version of Visual C++ in use."
3517 Output = FpArg->getValue();
3518
3519 // "If you do not specify an extension as part of the path name, an
3520 // extension of .pch is assumed. "
3521 if (!llvm::sys::path::has_extension(Output))
3522 Output += ".pch";
3523 } else {
3524 Output = BaseName;
3525 llvm::sys::path::replace_extension(Output, ".pch");
3526 }
3527 return Output.str();
3528}
3529
Chandler Carruth2ad5de12012-01-25 11:01:57 +00003530const ToolChain &Driver::getToolChain(const ArgList &Args,
Artem Belevich959e0542015-07-10 19:47:55 +00003531 const llvm::Triple &Target) const {
Chandler Carruth2ad5de12012-01-25 11:01:57 +00003532
Chandler Carruthd7fa2e02012-01-31 02:21:20 +00003533 ToolChain *&TC = ToolChains[Target.str()];
Chandler Carruth2ad5de12012-01-25 11:01:57 +00003534 if (!TC) {
3535 switch (Target.getOS()) {
Reid Kleckner330fb172016-05-11 16:19:05 +00003536 case llvm::Triple::Haiku:
3537 TC = new toolchains::Haiku(*this, Target, Args);
3538 break;
Ed Schouten3c3e58c2015-03-26 11:13:44 +00003539 case llvm::Triple::CloudABI:
3540 TC = new toolchains::CloudABI(*this, Target, Args);
3541 break;
Chandler Carruth2ad5de12012-01-25 11:01:57 +00003542 case llvm::Triple::Darwin:
3543 case llvm::Triple::MacOSX:
3544 case llvm::Triple::IOS:
Tim Northover6f3ff222015-10-30 16:30:27 +00003545 case llvm::Triple::TvOS:
3546 case llvm::Triple::WatchOS:
Rafael Espindola14627962013-11-24 23:28:23 +00003547 TC = new toolchains::DarwinClang(*this, Target, Args);
Chandler Carruth2ad5de12012-01-25 11:01:57 +00003548 break;
3549 case llvm::Triple::DragonFly:
Rafael Espindola1af7c212012-02-19 01:38:32 +00003550 TC = new toolchains::DragonFly(*this, Target, Args);
Chandler Carruth2ad5de12012-01-25 11:01:57 +00003551 break;
3552 case llvm::Triple::OpenBSD:
Rafael Espindola1af7c212012-02-19 01:38:32 +00003553 TC = new toolchains::OpenBSD(*this, Target, Args);
Chandler Carruth2ad5de12012-01-25 11:01:57 +00003554 break;
Eli Friedman9fa28852012-08-08 23:57:20 +00003555 case llvm::Triple::Bitrig:
3556 TC = new toolchains::Bitrig(*this, Target, Args);
3557 break;
Chandler Carruth2ad5de12012-01-25 11:01:57 +00003558 case llvm::Triple::NetBSD:
Rafael Espindola1af7c212012-02-19 01:38:32 +00003559 TC = new toolchains::NetBSD(*this, Target, Args);
Chandler Carruth2ad5de12012-01-25 11:01:57 +00003560 break;
3561 case llvm::Triple::FreeBSD:
Rafael Espindola1af7c212012-02-19 01:38:32 +00003562 TC = new toolchains::FreeBSD(*this, Target, Args);
Chandler Carruth2ad5de12012-01-25 11:01:57 +00003563 break;
3564 case llvm::Triple::Minix:
Rafael Espindola1af7c212012-02-19 01:38:32 +00003565 TC = new toolchains::Minix(*this, Target, Args);
Chandler Carruth2ad5de12012-01-25 11:01:57 +00003566 break;
3567 case llvm::Triple::Linux:
Andrey Turetskiy4798eb62016-06-16 10:36:09 +00003568 case llvm::Triple::ELFIAMCU:
Chandler Carruthcf705b22012-01-25 21:03:58 +00003569 if (Target.getArch() == llvm::Triple::hexagon)
Douglas Katzman54366072015-07-27 16:53:08 +00003570 TC = new toolchains::HexagonToolChain(*this, Target, Args);
Vasileios Kalintirisc744e122015-11-12 15:26:54 +00003571 else if ((Target.getVendor() == llvm::Triple::MipsTechnologies) &&
3572 !Target.hasEnvironment())
3573 TC = new toolchains::MipsLLVMToolChain(*this, Target, Args);
Chandler Carruthcf705b22012-01-25 21:03:58 +00003574 else
Rafael Espindola1af7c212012-02-19 01:38:32 +00003575 TC = new toolchains::Linux(*this, Target, Args);
Chandler Carruth2ad5de12012-01-25 11:01:57 +00003576 break;
Derek Schuff6ab52fa2015-03-30 20:31:33 +00003577 case llvm::Triple::NaCl:
Douglas Katzman54366072015-07-27 16:53:08 +00003578 TC = new toolchains::NaClToolChain(*this, Target, Args);
Derek Schuff6ab52fa2015-03-30 20:31:33 +00003579 break;
Petr Hosek62e1d232016-10-06 06:08:09 +00003580 case llvm::Triple::Fuchsia:
3581 TC = new toolchains::Fuchsia(*this, Target, Args);
3582 break;
David Chisnallf571cde2012-02-15 13:39:01 +00003583 case llvm::Triple::Solaris:
Rafael Espindola1af7c212012-02-19 01:38:32 +00003584 TC = new toolchains::Solaris(*this, Target, Args);
David Chisnallf571cde2012-02-15 13:39:01 +00003585 break;
Tom Stellard8fa33092015-07-18 01:49:05 +00003586 case llvm::Triple::AMDHSA:
3587 TC = new toolchains::AMDGPUToolChain(*this, Target, Args);
3588 break;
Chandler Carruth2ad5de12012-01-25 11:01:57 +00003589 case llvm::Triple::Win32:
Saleem Abdulrasool377066a2014-03-27 22:50:18 +00003590 switch (Target.getEnvironment()) {
3591 default:
3592 if (Target.isOSBinFormatELF())
3593 TC = new toolchains::Generic_ELF(*this, Target, Args);
3594 else if (Target.isOSBinFormatMachO())
3595 TC = new toolchains::MachO(*this, Target, Args);
3596 else
3597 TC = new toolchains::Generic_GCC(*this, Target, Args);
3598 break;
3599 case llvm::Triple::GNU:
Yaron Keren1c0070c2015-07-02 04:45:27 +00003600 TC = new toolchains::MinGW(*this, Target, Args);
Saleem Abdulrasool377066a2014-03-27 22:50:18 +00003601 break;
Saleem Abdulrasool543a78b2014-10-24 03:13:37 +00003602 case llvm::Triple::Itanium:
3603 TC = new toolchains::CrossWindowsToolChain(*this, Target, Args);
3604 break;
Saleem Abdulrasool377066a2014-03-27 22:50:18 +00003605 case llvm::Triple::MSVC:
3606 case llvm::Triple::UnknownEnvironment:
Saleem Abdulrasool819f3912014-10-22 02:37:29 +00003607 TC = new toolchains::MSVCToolChain(*this, Target, Args);
Saleem Abdulrasool377066a2014-03-27 22:50:18 +00003608 break;
3609 }
Chandler Carruth2ad5de12012-01-25 11:01:57 +00003610 break;
Artem Belevich0ff05cd2015-07-13 23:27:56 +00003611 case llvm::Triple::CUDA:
3612 TC = new toolchains::CudaToolChain(*this, Target, Args);
3613 break;
Filipe Cabecinhasc888e192015-10-14 12:25:43 +00003614 case llvm::Triple::PS4:
3615 TC = new toolchains::PS4CPU(*this, Target, Args);
3616 break;
David L Kreitzerd397ea42016-10-14 20:44:33 +00003617 case llvm::Triple::Contiki:
3618 TC = new toolchains::Contiki(*this, Target, Args);
3619 break;
Chandler Carruth2ad5de12012-01-25 11:01:57 +00003620 default:
Douglas Katzman9f5e70e2015-05-26 18:01:33 +00003621 // Of these targets, Hexagon is the only one that might have
3622 // an OS of Linux, in which case it got handled above already.
Douglas Katzman15a63ed2015-08-12 18:36:12 +00003623 switch (Target.getArch()) {
3624 case llvm::Triple::tce:
Rafael Espindola84b588b2013-03-18 18:10:27 +00003625 TC = new toolchains::TCEToolChain(*this, Target, Args);
Douglas Katzman15a63ed2015-08-12 18:36:12 +00003626 break;
3627 case llvm::Triple::hexagon:
Douglas Katzman54366072015-07-27 16:53:08 +00003628 TC = new toolchains::HexagonToolChain(*this, Target, Args);
Douglas Katzman15a63ed2015-08-12 18:36:12 +00003629 break;
Jacques Pienaard964cc22016-03-28 21:02:54 +00003630 case llvm::Triple::lanai:
3631 TC = new toolchains::LanaiToolChain(*this, Target, Args);
3632 break;
Douglas Katzman15a63ed2015-08-12 18:36:12 +00003633 case llvm::Triple::xcore:
Douglas Katzman54366072015-07-27 16:53:08 +00003634 TC = new toolchains::XCoreToolChain(*this, Target, Args);
Douglas Katzman15a63ed2015-08-12 18:36:12 +00003635 break;
Dan Gohmanc2853072015-09-03 22:51:53 +00003636 case llvm::Triple::wasm32:
3637 case llvm::Triple::wasm64:
3638 TC = new toolchains::WebAssembly(*this, Target, Args);
3639 break;
Douglas Katzman15a63ed2015-08-12 18:36:12 +00003640 default:
Douglas Katzmand6e597c2015-09-17 19:56:40 +00003641 if (Target.getVendor() == llvm::Triple::Myriad)
3642 TC = new toolchains::MyriadToolChain(*this, Target, Args);
3643 else if (Target.isOSBinFormatELF())
Douglas Katzman15a63ed2015-08-12 18:36:12 +00003644 TC = new toolchains::Generic_ELF(*this, Target, Args);
3645 else if (Target.isOSBinFormatMachO())
3646 TC = new toolchains::MachO(*this, Target, Args);
3647 else
3648 TC = new toolchains::Generic_GCC(*this, Target, Args);
3649 }
Chandler Carruth2ad5de12012-01-25 11:01:57 +00003650 }
3651 }
3652 return *TC;
Daniel Dunbar4dff6a42009-03-10 23:41:59 +00003653}
Daniel Dunbar8fa879d2009-03-24 18:57:02 +00003654
Rafael Espindola2f69d402013-03-18 15:33:26 +00003655bool Driver::ShouldUseClangCompiler(const JobAction &JA) const {
Douglas Katzman00249092015-06-12 15:45:21 +00003656 // Say "no" if there is not exactly one input of a type clang understands.
Nico Weber5a459f82016-02-23 19:30:43 +00003657 if (JA.size() != 1 ||
3658 !types::isAcceptedByClang((*JA.input_begin())->getType()))
Nick Lewycky5cc9ebb2012-11-15 05:36:36 +00003659 return false;
3660
Douglas Katzman00249092015-06-12 15:45:21 +00003661 // And say "no" if this is not a kind of action clang understands.
Nick Lewycky5cc9ebb2012-11-15 05:36:36 +00003662 if (!isa<PreprocessJobAction>(JA) && !isa<PrecompileJobAction>(JA) &&
Bob Wilson23a55f12014-12-21 07:00:00 +00003663 !isa<CompileJobAction>(JA) && !isa<BackendJobAction>(JA))
Nick Lewycky5cc9ebb2012-11-15 05:36:36 +00003664 return false;
3665
3666 return true;
3667}
3668
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00003669/// GetReleaseVersion - Parse (([0-9]+)(.([0-9]+)(.([0-9]+)?))?)? and return the
3670/// grouped values as integers. Numbers which are not provided are set to 0.
Daniel Dunbarc7fd57a2009-03-26 15:58:36 +00003671///
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00003672/// \return True if the entire string was parsed (9.2), or all groups were
3673/// parsed (10.3.5extrastuff).
Mehdi Amini12011172016-10-06 05:11:48 +00003674bool Driver::GetReleaseVersion(StringRef Str, unsigned &Major, unsigned &Minor,
3675 unsigned &Micro, bool &HadExtra) {
Daniel Dunbarc7fd57a2009-03-26 15:58:36 +00003676 HadExtra = false;
3677
3678 Major = Minor = Micro = 0;
Mehdi Amini12011172016-10-06 05:11:48 +00003679 if (Str.empty())
Bob Wilson433cb312015-04-07 01:03:35 +00003680 return false;
Daniel Dunbarc7fd57a2009-03-26 15:58:36 +00003681
Mehdi Amini12011172016-10-06 05:11:48 +00003682 if (Str.consumeInteger(10, Major))
3683 return false;
3684 if (Str.empty())
Daniel Dunbarc7fd57a2009-03-26 15:58:36 +00003685 return true;
Mehdi Amini12011172016-10-06 05:11:48 +00003686 if (Str[0] != '.')
Daniel Dunbarc7fd57a2009-03-26 15:58:36 +00003687 return false;
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00003688
Mehdi Amini12011172016-10-06 05:11:48 +00003689 Str = Str.drop_front(1);
Daniel Dunbarc7fd57a2009-03-26 15:58:36 +00003690
Mehdi Amini12011172016-10-06 05:11:48 +00003691 if (Str.consumeInteger(10, Minor))
Daniel Dunbarc7fd57a2009-03-26 15:58:36 +00003692 return false;
Mehdi Amini12011172016-10-06 05:11:48 +00003693 if (Str.empty())
3694 return true;
3695 if (Str[0] != '.')
3696 return false;
3697 Str = Str.drop_front(1);
3698
3699 if (Str.consumeInteger(10, Micro))
3700 return false;
3701 if (!Str.empty())
3702 HadExtra = true;
Daniel Dunbarc7fd57a2009-03-26 15:58:36 +00003703 return true;
3704}
Hans Wennborg6ddc6902013-07-27 00:23:45 +00003705
Bruno Cardoso Lopes8ed5cac2016-03-31 02:45:46 +00003706/// Parse digits from a string \p Str and fulfill \p Digits with
3707/// the parsed numbers. This method assumes that the max number of
3708/// digits to look for is equal to Digits.size().
3709///
3710/// \return True if the entire string was parsed and there are
3711/// no extra characters remaining at the end.
Mehdi Amini12011172016-10-06 05:11:48 +00003712bool Driver::GetReleaseVersion(StringRef Str,
Bruno Cardoso Lopes8ed5cac2016-03-31 02:45:46 +00003713 MutableArrayRef<unsigned> Digits) {
Mehdi Amini12011172016-10-06 05:11:48 +00003714 if (Str.empty())
Bruno Cardoso Lopes8ed5cac2016-03-31 02:45:46 +00003715 return false;
3716
Bruno Cardoso Lopes8ed5cac2016-03-31 02:45:46 +00003717 unsigned CurDigit = 0;
3718 while (CurDigit < Digits.size()) {
Mehdi Amini12011172016-10-06 05:11:48 +00003719 unsigned Digit;
3720 if (Str.consumeInteger(10, Digit))
Bruno Cardoso Lopes8ed5cac2016-03-31 02:45:46 +00003721 return false;
Mehdi Amini12011172016-10-06 05:11:48 +00003722 Digits[CurDigit] = Digit;
3723 if (Str.empty())
3724 return true;
3725 if (Str[0] != '.')
3726 return false;
3727 Str = Str.drop_front(1);
Bruno Cardoso Lopes8ed5cac2016-03-31 02:45:46 +00003728 CurDigit++;
3729 }
3730
3731 // More digits than requested, bail out...
3732 return false;
3733}
3734
Hans Wennborg6ddc6902013-07-27 00:23:45 +00003735std::pair<unsigned, unsigned> Driver::getIncludeExcludeOptionFlagMasks() const {
3736 unsigned IncludedFlagsBitmask = 0;
Rafael Espindolacc707bc2013-09-25 15:54:41 +00003737 unsigned ExcludedFlagsBitmask = options::NoDriverOption;
Hans Wennborg6ddc6902013-07-27 00:23:45 +00003738
3739 if (Mode == CLMode) {
Hans Wennborg19076102013-07-31 20:51:53 +00003740 // Include CL and Core options.
3741 IncludedFlagsBitmask |= options::CLOption;
3742 IncludedFlagsBitmask |= options::CoreOption;
Hans Wennborg6ddc6902013-07-27 00:23:45 +00003743 } else {
3744 ExcludedFlagsBitmask |= options::CLOption;
3745 }
3746
3747 return std::make_pair(IncludedFlagsBitmask, ExcludedFlagsBitmask);
3748}
Benjamin Kramerab88f622014-03-25 18:02:07 +00003749
Douglas Katzmanf08fadf2015-06-04 14:40:44 +00003750bool clang::driver::isOptimizationLevelFast(const ArgList &Args) {
Benjamin Kramerab88f622014-03-25 18:02:07 +00003751 return Args.hasFlag(options::OPT_Ofast, options::OPT_O_Group, false);
3752}