blob: 729209cf50994d666848e35498a45b9128d4c5ac [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>
Bruno Cardoso Lopes02681c42016-11-17 21:41:22 +000045#if LLVM_ON_UNIX
46#include <unistd.h> // getpid
47#endif
Dylan Noblesmith86780e92012-02-01 14:25:28 +000048
Daniel Dunbarb2cd66b2009-03-04 20:49:20 +000049using namespace clang::driver;
Chris Lattnerada1c912009-03-26 05:56:24 +000050using namespace clang;
Reid Kleckner898229a2013-06-14 17:17:23 +000051using namespace llvm::opt;
Daniel Dunbarb2cd66b2009-03-04 20:49:20 +000052
Reid Kleckner68eb60b2015-02-02 22:41:48 +000053Driver::Driver(StringRef ClangExecutable, StringRef DefaultTargetTriple,
Benjamin Kramerd45b2052015-10-07 15:48:01 +000054 DiagnosticsEngine &Diags,
55 IntrusiveRefCntPtr<vfs::FileSystem> VFS)
Benjamin Kramercfeacf52016-05-27 14:27:13 +000056 : Opts(createDriverOptTable()), Diags(Diags), VFS(std::move(VFS)),
57 Mode(GCCMode), SaveTemps(SaveTempsNone), BitcodeEmbed(EmbedNone),
58 LTOMode(LTOK_None), ClangExecutable(ClangExecutable),
Reid Kleckner68eb60b2015-02-02 22:41:48 +000059 SysRoot(DEFAULT_SYSROOT), UseStdLib(true),
Reid Kleckner68eb60b2015-02-02 22:41:48 +000060 DriverTitle("clang LLVM compiler"), CCPrintOptionsFilename(nullptr),
61 CCPrintHeadersFilename(nullptr), CCLogDiagnosticsFilename(nullptr),
62 CCCPrintBindings(false), CCPrintHeaders(false), CCLogDiagnostics(false),
Vedant Kumarf2030b92016-07-18 19:56:33 +000063 CCGenDiagnostics(false), DefaultTargetTriple(DefaultTargetTriple),
64 CCCGenericGCCName(""), CheckInputsExist(true), CCCUsePCH(true),
65 SuppressMissingInputWarning(false) {
Daniel Dunbar3f3e2cd2010-01-20 02:35:16 +000066
Benjamin Kramerd45b2052015-10-07 15:48:01 +000067 // Provide a sane fallback if no VFS is specified.
68 if (!this->VFS)
69 this->VFS = vfs::getRealFileSystem();
70
Sumanth Gundapaneni3a1592942015-03-03 20:43:12 +000071 Name = llvm::sys::path::filename(ClangExecutable);
Douglas Katzmana67e50c2015-06-26 15:47:46 +000072 Dir = llvm::sys::path::parent_path(ClangExecutable);
Benjamin Kramerf420dda2015-10-13 15:19:32 +000073 InstalledDir = Dir; // Provide a sensible default installed dir.
Bob Wilsona20a1da2013-03-23 05:17:59 +000074
75 // Compute the path to the resource directory.
76 StringRef ClangResourceDir(CLANG_RESOURCE_DIR);
77 SmallString<128> P(Dir);
Chandler Carruthfd3cc702014-12-29 12:09:08 +000078 if (ClangResourceDir != "") {
Bob Wilsona20a1da2013-03-23 05:17:59 +000079 llvm::sys::path::append(P, ClangResourceDir);
Chandler Carruthfd3cc702014-12-29 12:09:08 +000080 } else {
81 StringRef ClangLibdirSuffix(CLANG_LIBDIR_SUFFIX);
82 llvm::sys::path::append(P, "..", Twine("lib") + ClangLibdirSuffix, "clang",
83 CLANG_VERSION_STRING);
84 }
Bob Wilsona20a1da2013-03-23 05:17:59 +000085 ResourceDir = P.str();
Daniel Dunbar544ecd12009-03-02 19:59:07 +000086}
87
88Driver::~Driver() {
Reid Kleckner588c9372014-02-19 23:44:52 +000089 llvm::DeleteContainerSeconds(ToolChains);
Daniel Dunbar544ecd12009-03-02 19:59:07 +000090}
91
Zachary Turneraff19c32016-08-12 17:47:52 +000092void Driver::ParseDriverMode(StringRef ProgramName,
93 ArrayRef<const char *> Args) {
94 auto Default = ToolChain::getTargetAndModeFromProgramName(ProgramName);
95 StringRef DefaultMode(Default.second);
96 setDriverModeFromOption(DefaultMode);
Hans Wennborg70850d82013-07-18 20:29:38 +000097
Douglas Katzman6bbffc42015-06-25 18:51:37 +000098 for (const char *ArgPtr : Args) {
Reid Kleckneraf5fd6a2014-08-22 19:29:30 +000099 // Ingore nullptrs, they are response file's EOL markers
Douglas Katzman6bbffc42015-06-25 18:51:37 +0000100 if (ArgPtr == nullptr)
Reid Kleckneraf5fd6a2014-08-22 19:29:30 +0000101 continue;
Douglas Katzman6bbffc42015-06-25 18:51:37 +0000102 const StringRef Arg = ArgPtr;
Zachary Turneraff19c32016-08-12 17:47:52 +0000103 setDriverModeFromOption(Arg);
Hans Wennborg70850d82013-07-18 20:29:38 +0000104 }
105}
106
Zachary Turneraff19c32016-08-12 17:47:52 +0000107void Driver::setDriverModeFromOption(StringRef Opt) {
108 const std::string OptName =
109 getOpts().getOption(options::OPT_driver_mode).getPrefixedName();
110 if (!Opt.startswith(OptName))
111 return;
112 StringRef Value = Opt.drop_front(OptName.size());
113
114 const unsigned M = llvm::StringSwitch<unsigned>(Value)
115 .Case("gcc", GCCMode)
116 .Case("g++", GXXMode)
117 .Case("cpp", CPPMode)
118 .Case("cl", CLMode)
119 .Default(~0U);
120
121 if (M != ~0U)
122 Mode = static_cast<DriverMode>(M);
123 else
124 Diag(diag::err_drv_unsupported_option_argument) << OptName << Value;
125}
126
David Blaikie69a1d8c2015-06-22 22:07:27 +0000127InputArgList Driver::ParseArgStrings(ArrayRef<const char *> ArgStrings) {
Daniel Dunbar2608c542009-03-18 01:38:48 +0000128 llvm::PrettyStackTraceString CrashInfo("Command line argument parsing");
Hans Wennborg6ddc6902013-07-27 00:23:45 +0000129
130 unsigned IncludedFlagsBitmask;
131 unsigned ExcludedFlagsBitmask;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +0000132 std::tie(IncludedFlagsBitmask, ExcludedFlagsBitmask) =
Douglas Katzmana67e50c2015-06-26 15:47:46 +0000133 getIncludeExcludeOptionFlagMasks();
Hans Wennborg6ddc6902013-07-27 00:23:45 +0000134
Daniel Dunbar52ed5fe2009-11-19 06:35:06 +0000135 unsigned MissingArgIndex, MissingArgCount;
David Blaikie69a1d8c2015-06-22 22:07:27 +0000136 InputArgList Args =
David Blaikie6d492ad2015-06-21 06:32:36 +0000137 getOpts().ParseArgs(ArgStrings, MissingArgIndex, MissingArgCount,
138 IncludedFlagsBitmask, ExcludedFlagsBitmask);
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +0000139
Daniel Dunbar52ed5fe2009-11-19 06:35:06 +0000140 // Check for missing argument error.
141 if (MissingArgCount)
142 Diag(clang::diag::err_drv_missing_argument)
David Blaikie69a1d8c2015-06-22 22:07:27 +0000143 << Args.getArgString(MissingArgIndex) << MissingArgCount;
Daniel Dunbar65229332009-03-13 11:38:42 +0000144
Daniel Dunbar52ed5fe2009-11-19 06:35:06 +0000145 // Check for unsupported options.
David Blaikie69a1d8c2015-06-22 22:07:27 +0000146 for (const Arg *A : Args) {
Michael J. Spencer66e2b202012-10-19 22:37:06 +0000147 if (A->getOption().hasFlag(options::Unsupported)) {
David Blaikie69a1d8c2015-06-22 22:07:27 +0000148 Diag(clang::diag::err_drv_unsupported_opt) << A->getAsString(Args);
Daniel Dunbard8500f32009-03-22 23:26:43 +0000149 continue;
150 }
Chad Rosierce975d92012-02-22 17:55:22 +0000151
152 // Warn about -mcpu= without an argument.
Douglas Katzmana67e50c2015-06-26 15:47:46 +0000153 if (A->getOption().matches(options::OPT_mcpu_EQ) && A->containsValue("")) {
David Blaikie69a1d8c2015-06-22 22:07:27 +0000154 Diag(clang::diag::warn_drv_empty_joined_argument) << A->getAsString(Args);
Chad Rosierce975d92012-02-22 17:55:22 +0000155 }
Daniel Dunbard02cb1d2009-03-05 06:38:47 +0000156 }
157
David Blaikie69a1d8c2015-06-22 22:07:27 +0000158 for (const Arg *A : Args.filtered(options::OPT_UNKNOWN))
Ehsan Akhgarid8518332016-01-25 21:14:52 +0000159 Diags.Report(IsCLMode() ? diag::warn_drv_unknown_argument_clang_cl :
160 diag::err_drv_unknown_argument)
161 << A->getAsString(Args);
Rafael Espindola8a2d4962013-09-23 23:55:25 +0000162
Daniel Dunbard02cb1d2009-03-05 06:38:47 +0000163 return Args;
164}
165
Chad Rosier7742b5d2011-07-27 23:36:45 +0000166// Determine which compilation mode we are in. We look for options which
167// affect the phase, starting with the earliest phases, and record which
168// option we used to determine the final phase.
Douglas Katzmana67e50c2015-06-26 15:47:46 +0000169phases::ID Driver::getFinalPhase(const DerivedArgList &DAL,
170 Arg **FinalPhaseArg) const {
Craig Topper92fc2df2014-05-17 16:56:41 +0000171 Arg *PhaseArg = nullptr;
Chad Rosier7742b5d2011-07-27 23:36:45 +0000172 phases::ID FinalPhase;
Eric Christopherf901e852011-08-17 22:59:59 +0000173
Hans Wennborge50cec32014-06-13 20:59:54 +0000174 // -{E,EP,P,M,MM} only run the preprocessor.
Douglas Katzmana67e50c2015-06-26 15:47:46 +0000175 if (CCCIsCPP() || (PhaseArg = DAL.getLastArg(options::OPT_E)) ||
Hans Wennborge50cec32014-06-13 20:59:54 +0000176 (PhaseArg = DAL.getLastArg(options::OPT__SLASH_EP)) ||
Hans Wennborge0053472013-12-20 18:40:46 +0000177 (PhaseArg = DAL.getLastArg(options::OPT_M, options::OPT_MM)) ||
178 (PhaseArg = DAL.getLastArg(options::OPT__SLASH_P))) {
Chad Rosier7742b5d2011-07-27 23:36:45 +0000179 FinalPhase = phases::Preprocess;
Eric Christopherf901e852011-08-17 22:59:59 +0000180
Richard Smithdd4ad3d2016-08-30 19:06:26 +0000181 // --precompile only runs up to precompilation.
182 } else if ((PhaseArg = DAL.getLastArg(options::OPT__precompile))) {
183 FinalPhase = phases::Precompile;
184
Bob Wilson23a55f12014-12-21 07:00:00 +0000185 // -{fsyntax-only,-analyze,emit-ast} only run up to the compiler.
Chad Rosier7742b5d2011-07-27 23:36:45 +0000186 } else if ((PhaseArg = DAL.getLastArg(options::OPT_fsyntax_only)) ||
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +0000187 (PhaseArg = DAL.getLastArg(options::OPT_module_file_info)) ||
Ben Langmuir2cb4a782014-02-05 22:21:15 +0000188 (PhaseArg = DAL.getLastArg(options::OPT_verify_pch)) ||
Chad Rosier7742b5d2011-07-27 23:36:45 +0000189 (PhaseArg = DAL.getLastArg(options::OPT_rewrite_objc)) ||
Fariborz Jahanian73223bb2012-04-02 15:59:19 +0000190 (PhaseArg = DAL.getLastArg(options::OPT_rewrite_legacy_objc)) ||
Ted Kremenekf7639e12012-03-06 20:06:33 +0000191 (PhaseArg = DAL.getLastArg(options::OPT__migrate)) ||
Chad Rosier7742b5d2011-07-27 23:36:45 +0000192 (PhaseArg = DAL.getLastArg(options::OPT__analyze,
Chad Rosier1aeb15a2012-03-06 23:14:35 +0000193 options::OPT__analyze_auto)) ||
Bob Wilson23a55f12014-12-21 07:00:00 +0000194 (PhaseArg = DAL.getLastArg(options::OPT_emit_ast))) {
Chad Rosier7742b5d2011-07-27 23:36:45 +0000195 FinalPhase = phases::Compile;
196
Bob Wilson23a55f12014-12-21 07:00:00 +0000197 // -S only runs up to the backend.
198 } else if ((PhaseArg = DAL.getLastArg(options::OPT_S))) {
199 FinalPhase = phases::Backend;
200
Artem Belevich4242f412015-07-28 21:01:21 +0000201 // -c compilation only runs up to the assembler.
202 } else if ((PhaseArg = DAL.getLastArg(options::OPT_c))) {
Chad Rosier7742b5d2011-07-27 23:36:45 +0000203 FinalPhase = phases::Assemble;
204
205 // Otherwise do everything.
206 } else
207 FinalPhase = phases::Link;
208
209 if (FinalPhaseArg)
210 *FinalPhaseArg = PhaseArg;
211
212 return FinalPhase;
213}
214
David Blaikie0aaa7622017-01-13 17:34:15 +0000215static Arg *MakeInputArg(DerivedArgList &Args, OptTable &Opts,
Hans Wennborged1d0722013-08-13 21:32:29 +0000216 StringRef Value) {
David Blaikie0aaa7622017-01-13 17:34:15 +0000217 Arg *A = new Arg(Opts.getOption(options::OPT_INPUT), Value,
Hans Wennborged1d0722013-08-13 21:32:29 +0000218 Args.getBaseArgs().MakeIndex(Value), Value.data());
Hans Wennborg55362852014-05-02 22:55:30 +0000219 Args.AddSynthesizedArg(A);
Hans Wennborged1d0722013-08-13 21:32:29 +0000220 A->claim();
221 return A;
222}
223
Daniel Dunbar775d4062010-06-11 22:00:26 +0000224DerivedArgList *Driver::TranslateInputArgs(const InputArgList &Args) const {
225 DerivedArgList *DAL = new DerivedArgList(Args);
226
Daniel Dunbar2cc3f172010-09-17 00:45:02 +0000227 bool HasNostdlib = Args.hasArg(options::OPT_nostdlib);
Nirav Daveb0bb6142015-11-24 16:07:21 +0000228 bool HasNodefaultlib = Args.hasArg(options::OPT_nodefaultlibs);
Saleem Abdulrasool688b6bc2014-12-29 19:01:36 +0000229 for (Arg *A : Args) {
Daniel Dunbarfb3d7472010-06-14 21:23:12 +0000230 // Unfortunately, we have to parse some forwarding options (-Xassembler,
231 // -Xlinker, -Xpreprocessor) because we either integrate their functionality
232 // (assembler and preprocessor), or bypass a previous driver ('collect2').
Daniel Dunbar5a9d1832010-06-14 21:37:09 +0000233
234 // Rewrite linker options, to replace --no-demangle with a custom internal
235 // option.
236 if ((A->getOption().matches(options::OPT_Wl_COMMA) ||
237 A->getOption().matches(options::OPT_Xlinker)) &&
238 A->containsValue("--no-demangle")) {
Daniel Dunbarfb3d7472010-06-14 21:23:12 +0000239 // Add the rewritten no-demangle argument.
240 DAL->AddFlagArg(A, Opts->getOption(options::OPT_Z_Xlinker__no_demangle));
241
242 // Add the remaining values as Xlinker arguments.
Benjamin Kramer72e64312015-09-24 14:48:49 +0000243 for (StringRef Val : A->getValues())
Douglas Katzmana34b7bf2015-06-30 19:32:57 +0000244 if (Val != "--no-demangle")
245 DAL->AddSeparateArg(A, Opts->getOption(options::OPT_Xlinker), Val);
Daniel Dunbarfb3d7472010-06-14 21:23:12 +0000246
247 continue;
248 }
249
Daniel Dunbar5a9d1832010-06-14 21:37:09 +0000250 // Rewrite preprocessor options, to replace -Wp,-MD,FOO which is used by
251 // some build systems. We don't try to be complete here because we don't
252 // care to encourage this usage model.
253 if (A->getOption().matches(options::OPT_Wp_COMMA) &&
Richard Smithbd55daf2012-11-01 04:30:05 +0000254 (A->getValue(0) == StringRef("-MD") ||
255 A->getValue(0) == StringRef("-MMD"))) {
Daniel Dunbar3648ba72010-06-15 20:30:18 +0000256 // Rewrite to -MD/-MMD along with -MF.
Richard Smithbd55daf2012-11-01 04:30:05 +0000257 if (A->getValue(0) == StringRef("-MD"))
Daniel Dunbar3648ba72010-06-15 20:30:18 +0000258 DAL->AddFlagArg(A, Opts->getOption(options::OPT_MD));
259 else
260 DAL->AddFlagArg(A, Opts->getOption(options::OPT_MMD));
Michael J. Spencer70d85be2012-11-07 23:37:14 +0000261 if (A->getNumValues() == 2)
262 DAL->AddSeparateArg(A, Opts->getOption(options::OPT_MF),
263 A->getValue(1));
Daniel Dunbar5a9d1832010-06-14 21:37:09 +0000264 continue;
265 }
266
Shantonu Senafeb03b2010-09-17 18:39:08 +0000267 // Rewrite reserved library names.
268 if (A->getOption().matches(options::OPT_l)) {
Richard Smithbd55daf2012-11-01 04:30:05 +0000269 StringRef Value = A->getValue();
Daniel Dunbar2cc3f172010-09-17 00:45:02 +0000270
Shantonu Senafeb03b2010-09-17 18:39:08 +0000271 // Rewrite unless -nostdlib is present.
Nirav Daveb0bb6142015-11-24 16:07:21 +0000272 if (!HasNostdlib && !HasNodefaultlib && Value == "stdc++") {
Douglas Katzmana67e50c2015-06-26 15:47:46 +0000273 DAL->AddFlagArg(A, Opts->getOption(options::OPT_Z_reserved_lib_stdcxx));
Daniel Dunbar2cc3f172010-09-17 00:45:02 +0000274 continue;
275 }
Shantonu Senafeb03b2010-09-17 18:39:08 +0000276
277 // Rewrite unconditionally.
278 if (Value == "cc_kext") {
Douglas Katzmana67e50c2015-06-26 15:47:46 +0000279 DAL->AddFlagArg(A, Opts->getOption(options::OPT_Z_reserved_lib_cckext));
Shantonu Senafeb03b2010-09-17 18:39:08 +0000280 continue;
281 }
Daniel Dunbar2cc3f172010-09-17 00:45:02 +0000282 }
283
Hans Wennborged1d0722013-08-13 21:32:29 +0000284 // Pick up inputs via the -- option.
285 if (A->getOption().matches(options::OPT__DASH_DASH)) {
286 A->claim();
Benjamin Kramer72e64312015-09-24 14:48:49 +0000287 for (StringRef Val : A->getValues())
David Blaikie0aaa7622017-01-13 17:34:15 +0000288 DAL->append(MakeInputArg(*DAL, *Opts, Val));
Hans Wennborged1d0722013-08-13 21:32:29 +0000289 continue;
290 }
291
Saleem Abdulrasool688b6bc2014-12-29 19:01:36 +0000292 DAL->append(A);
Daniel Dunbarfb3d7472010-06-14 21:23:12 +0000293 }
Daniel Dunbar775d4062010-06-11 22:00:26 +0000294
Andrey Turetskiy6a8b91d2016-04-21 10:16:48 +0000295 // Enforce -static if -miamcu is present.
Andrey Turetskiy5fea71c2016-06-29 10:57:17 +0000296 if (Args.hasFlag(options::OPT_miamcu, options::OPT_mno_iamcu, false))
297 DAL->AddFlagArg(0, Opts->getOption(options::OPT_static));
Andrey Turetskiy6a8b91d2016-04-21 10:16:48 +0000298
Douglas Katzmana67e50c2015-06-26 15:47:46 +0000299// Add a default value of -mlinker-version=, if one was given and the user
300// didn't specify one.
Daniel Dunbar628fcf42010-08-12 00:05:12 +0000301#if defined(HOST_LINK_VERSION)
Tim Northover018578c2015-06-12 19:21:35 +0000302 if (!Args.hasArg(options::OPT_mlinker_version_EQ) &&
303 strlen(HOST_LINK_VERSION) > 0) {
Daniel Dunbar628fcf42010-08-12 00:05:12 +0000304 DAL->AddJoinedArg(0, Opts->getOption(options::OPT_mlinker_version_EQ),
305 HOST_LINK_VERSION);
Daniel Dunbarb613ffc2010-08-17 22:32:45 +0000306 DAL->getLastArg(options::OPT_mlinker_version_EQ)->claim();
Daniel Dunbar628fcf42010-08-12 00:05:12 +0000307 }
308#endif
309
Daniel Dunbar775d4062010-06-11 22:00:26 +0000310 return DAL;
311}
312
Artem Belevich959e0542015-07-10 19:47:55 +0000313/// \brief Compute target triple from args.
314///
315/// This routine provides the logic to compute a target triple from various
316/// args passed to the driver and the default triple string.
Andrey Turetskiy6a8b91d2016-04-21 10:16:48 +0000317static llvm::Triple computeTargetTriple(const Driver &D,
318 StringRef DefaultTargetTriple,
Artem Belevich959e0542015-07-10 19:47:55 +0000319 const ArgList &Args,
320 StringRef DarwinArchName = "") {
321 // FIXME: Already done in Compilation *Driver::BuildCompilation
322 if (const Arg *A = Args.getLastArg(options::OPT_target))
323 DefaultTargetTriple = A->getValue();
324
325 llvm::Triple Target(llvm::Triple::normalize(DefaultTargetTriple));
326
327 // Handle Apple-specific options available here.
328 if (Target.isOSBinFormatMachO()) {
329 // If an explict Darwin arch name is given, that trumps all.
330 if (!DarwinArchName.empty()) {
331 tools::darwin::setTripleTypeForMachOArchName(Target, DarwinArchName);
332 return Target;
333 }
334
335 // Handle the Darwin '-arch' flag.
336 if (Arg *A = Args.getLastArg(options::OPT_arch)) {
337 StringRef ArchName = A->getValue();
338 tools::darwin::setTripleTypeForMachOArchName(Target, ArchName);
339 }
340 }
341
342 // Handle pseudo-target flags '-mlittle-endian'/'-EL' and
343 // '-mbig-endian'/'-EB'.
344 if (Arg *A = Args.getLastArg(options::OPT_mlittle_endian,
345 options::OPT_mbig_endian)) {
346 if (A->getOption().matches(options::OPT_mlittle_endian)) {
347 llvm::Triple LE = Target.getLittleEndianArchVariant();
348 if (LE.getArch() != llvm::Triple::UnknownArch)
349 Target = std::move(LE);
350 } else {
351 llvm::Triple BE = Target.getBigEndianArchVariant();
352 if (BE.getArch() != llvm::Triple::UnknownArch)
353 Target = std::move(BE);
354 }
355 }
356
357 // Skip further flag support on OSes which don't support '-m32' or '-m64'.
Douglas Katzman15a63ed2015-08-12 18:36:12 +0000358 if (Target.getArch() == llvm::Triple::tce ||
359 Target.getOS() == llvm::Triple::Minix)
Artem Belevich959e0542015-07-10 19:47:55 +0000360 return Target;
361
362 // Handle pseudo-target flags '-m64', '-mx32', '-m32' and '-m16'.
Andrey Turetskiy6a8b91d2016-04-21 10:16:48 +0000363 Arg *A = Args.getLastArg(options::OPT_m64, options::OPT_mx32,
364 options::OPT_m32, options::OPT_m16);
365 if (A) {
Artem Belevich959e0542015-07-10 19:47:55 +0000366 llvm::Triple::ArchType AT = llvm::Triple::UnknownArch;
367
368 if (A->getOption().matches(options::OPT_m64)) {
369 AT = Target.get64BitArchVariant().getArch();
370 if (Target.getEnvironment() == llvm::Triple::GNUX32)
371 Target.setEnvironment(llvm::Triple::GNU);
372 } else if (A->getOption().matches(options::OPT_mx32) &&
373 Target.get64BitArchVariant().getArch() == llvm::Triple::x86_64) {
374 AT = llvm::Triple::x86_64;
375 Target.setEnvironment(llvm::Triple::GNUX32);
376 } else if (A->getOption().matches(options::OPT_m32)) {
377 AT = Target.get32BitArchVariant().getArch();
378 if (Target.getEnvironment() == llvm::Triple::GNUX32)
379 Target.setEnvironment(llvm::Triple::GNU);
380 } else if (A->getOption().matches(options::OPT_m16) &&
381 Target.get32BitArchVariant().getArch() == llvm::Triple::x86) {
382 AT = llvm::Triple::x86;
383 Target.setEnvironment(llvm::Triple::CODE16);
384 }
385
386 if (AT != llvm::Triple::UnknownArch && AT != Target.getArch())
387 Target.setArch(AT);
388 }
389
Andrey Turetskiy6a8b91d2016-04-21 10:16:48 +0000390 // Handle -miamcu flag.
Andrey Turetskiy5fea71c2016-06-29 10:57:17 +0000391 if (Args.hasFlag(options::OPT_miamcu, options::OPT_mno_iamcu, false)) {
392 if (Target.get32BitArchVariant().getArch() != llvm::Triple::x86)
393 D.Diag(diag::err_drv_unsupported_opt_for_target) << "-miamcu"
394 << Target.str();
Andrey Turetskiy6a8b91d2016-04-21 10:16:48 +0000395
Andrey Turetskiy5fea71c2016-06-29 10:57:17 +0000396 if (A && !A->getOption().matches(options::OPT_m32))
397 D.Diag(diag::err_drv_argument_not_allowed_with)
398 << "-miamcu" << A->getBaseArg().getAsString(Args);
Andrey Turetskiy6a8b91d2016-04-21 10:16:48 +0000399
Andrey Turetskiy5fea71c2016-06-29 10:57:17 +0000400 Target.setArch(llvm::Triple::x86);
401 Target.setArchName("i586");
402 Target.setEnvironment(llvm::Triple::UnknownEnvironment);
403 Target.setEnvironmentName("");
404 Target.setOS(llvm::Triple::ELFIAMCU);
405 Target.setVendor(llvm::Triple::UnknownVendor);
406 Target.setVendorName("intel");
Andrey Turetskiy6a8b91d2016-04-21 10:16:48 +0000407 }
408
Artem Belevich959e0542015-07-10 19:47:55 +0000409 return Target;
410}
411
Teresa Johnson945bc502015-10-15 20:35:53 +0000412// \brief Parse the LTO options and record the type of LTO compilation
413// based on which -f(no-)?lto(=.*)? option occurs last.
414void Driver::setLTOMode(const llvm::opt::ArgList &Args) {
415 LTOMode = LTOK_None;
416 if (!Args.hasFlag(options::OPT_flto, options::OPT_flto_EQ,
417 options::OPT_fno_lto, false))
418 return;
419
420 StringRef LTOName("full");
421
422 const Arg *A = Args.getLastArg(options::OPT_flto_EQ);
Teresa Johnson6ef80dc2015-11-02 18:03:12 +0000423 if (A)
424 LTOName = A->getValue();
Teresa Johnson945bc502015-10-15 20:35:53 +0000425
426 LTOMode = llvm::StringSwitch<LTOKind>(LTOName)
427 .Case("full", LTOK_Full)
428 .Case("thin", LTOK_Thin)
429 .Default(LTOK_Unknown);
430
431 if (LTOMode == LTOK_Unknown) {
432 assert(A);
433 Diag(diag::err_drv_unsupported_option_argument) << A->getOption().getName()
434 << A->getValue();
435 }
436}
437
Samuel Antao39f9da22016-10-27 16:38:05 +0000438/// Compute the desired OpenMP runtime from the flags provided.
439Driver::OpenMPRuntimeKind Driver::getOpenMPRuntime(const ArgList &Args) const {
440 StringRef RuntimeName(CLANG_DEFAULT_OPENMP_RUNTIME);
441
442 const Arg *A = Args.getLastArg(options::OPT_fopenmp_EQ);
443 if (A)
444 RuntimeName = A->getValue();
445
446 auto RT = llvm::StringSwitch<OpenMPRuntimeKind>(RuntimeName)
447 .Case("libomp", OMPRT_OMP)
448 .Case("libgomp", OMPRT_GOMP)
449 .Case("libiomp5", OMPRT_IOMP5)
450 .Default(OMPRT_Unknown);
451
452 if (RT == OMPRT_Unknown) {
453 if (A)
454 Diag(diag::err_drv_unsupported_option_argument)
455 << A->getOption().getName() << A->getValue();
456 else
457 // FIXME: We could use a nicer diagnostic here.
458 Diag(diag::err_drv_unsupported_opt) << "-fopenmp";
459 }
460
461 return RT;
462}
463
Samuel Antaoc1ffba52016-06-13 18:10:57 +0000464void Driver::CreateOffloadingDeviceToolChains(Compilation &C,
465 InputList &Inputs) {
466
467 //
468 // CUDA
469 //
470 // We need to generate a CUDA toolchain if any of the inputs has a CUDA type.
471 if (llvm::any_of(Inputs, [](std::pair<types::ID, const llvm::opt::Arg *> &I) {
472 return types::isCuda(I.first);
473 })) {
Justin Lebar66c4fd72016-11-18 00:41:22 +0000474 const ToolChain *HostTC = C.getSingleOffloadToolChain<Action::OFK_Host>();
475 const llvm::Triple &HostTriple = HostTC->getTriple();
476 llvm::Triple CudaTriple(HostTriple.isArch64Bit() ? "nvptx64-nvidia-cuda"
477 : "nvptx-nvidia-cuda");
478 // Use the CUDA and host triples as the key into the ToolChains map, because
479 // the device toolchain we create depends on both.
480 ToolChain *&CudaTC = ToolChains[CudaTriple.str() + "/" + HostTriple.str()];
481 if (!CudaTC) {
482 CudaTC = new toolchains::CudaToolChain(*this, CudaTriple, *HostTC,
483 C.getInputArgs());
484 }
485 C.addOffloadDeviceToolChain(CudaTC, Action::OFK_Cuda);
Samuel Antaoc1ffba52016-06-13 18:10:57 +0000486 }
487
488 //
Samuel Antao39f9da22016-10-27 16:38:05 +0000489 // OpenMP
490 //
491 // We need to generate an OpenMP toolchain if the user specified targets with
492 // the -fopenmp-targets option.
493 if (Arg *OpenMPTargets =
494 C.getInputArgs().getLastArg(options::OPT_fopenmp_targets_EQ)) {
495 if (OpenMPTargets->getNumValues()) {
496 // We expect that -fopenmp-targets is always used in conjunction with the
497 // option -fopenmp specifying a valid runtime with offloading support,
498 // i.e. libomp or libiomp.
499 bool HasValidOpenMPRuntime = C.getInputArgs().hasFlag(
500 options::OPT_fopenmp, options::OPT_fopenmp_EQ,
501 options::OPT_fno_openmp, false);
502 if (HasValidOpenMPRuntime) {
503 OpenMPRuntimeKind OpenMPKind = getOpenMPRuntime(C.getInputArgs());
504 HasValidOpenMPRuntime =
505 OpenMPKind == OMPRT_OMP || OpenMPKind == OMPRT_IOMP5;
506 }
507
508 if (HasValidOpenMPRuntime) {
509 llvm::StringMap<const char *> FoundNormalizedTriples;
510 for (const char *Val : OpenMPTargets->getValues()) {
511 llvm::Triple TT(Val);
512 std::string NormalizedName = TT.normalize();
513
514 // Make sure we don't have a duplicate triple.
515 auto Duplicate = FoundNormalizedTriples.find(NormalizedName);
516 if (Duplicate != FoundNormalizedTriples.end()) {
517 Diag(clang::diag::warn_drv_omp_offload_target_duplicate)
518 << Val << Duplicate->second;
519 continue;
520 }
521
522 // Store the current triple so that we can check for duplicates in the
523 // following iterations.
524 FoundNormalizedTriples[NormalizedName] = Val;
525
526 // If the specified target is invalid, emit a diagnostic.
527 if (TT.getArch() == llvm::Triple::UnknownArch)
528 Diag(clang::diag::err_drv_invalid_omp_target) << Val;
529 else {
530 const ToolChain &TC = getToolChain(C.getInputArgs(), TT);
531 C.addOffloadDeviceToolChain(&TC, Action::OFK_OpenMP);
532 }
533 }
534 } else
535 Diag(clang::diag::err_drv_expecting_fopenmp_with_fopenmp_targets);
536 } else
537 Diag(clang::diag::warn_drv_empty_joined_argument)
538 << OpenMPTargets->getAsString(C.getInputArgs());
539 }
540
541 //
Samuel Antaoc1ffba52016-06-13 18:10:57 +0000542 // TODO: Add support for other offloading programming models here.
543 //
544
545 return;
546}
547
Chris Lattner54b16772011-07-23 17:14:25 +0000548Compilation *Driver::BuildCompilation(ArrayRef<const char *> ArgList) {
Daniel Dunbar2608c542009-03-18 01:38:48 +0000549 llvm::PrettyStackTraceString CrashInfo("Compilation construction");
550
Eric Christopherf901e852011-08-17 22:59:59 +0000551 // FIXME: Handle environment options which affect driver behavior, somewhere
Bill Wendlingadbeb9f2012-03-12 21:24:57 +0000552 // (client?). GCC_EXEC_PREFIX, LPATH, CC_PRINT_OPTIONS.
Chad Rosier82301162011-09-14 00:47:55 +0000553
David Majnemer85c25b42016-07-24 17:44:03 +0000554 if (Optional<std::string> CompilerPathValue =
555 llvm::sys::Process::GetEnv("COMPILER_PATH")) {
556 StringRef CompilerPath = *CompilerPathValue;
Chad Rosier82301162011-09-14 00:47:55 +0000557 while (!CompilerPath.empty()) {
Douglas Katzmana67e50c2015-06-26 15:47:46 +0000558 std::pair<StringRef, StringRef> Split =
559 CompilerPath.split(llvm::sys::EnvPathSeparator);
Chad Rosier82301162011-09-14 00:47:55 +0000560 PrefixDirs.push_back(Split.first);
561 CompilerPath = Split.second;
562 }
563 }
Daniel Dunbar5e0f6af2009-03-13 00:51:18 +0000564
Hans Wennborg70850d82013-07-18 20:29:38 +0000565 // We look for the driver mode option early, because the mode can affect
566 // how other options are parsed.
Zachary Turneraff19c32016-08-12 17:47:52 +0000567 ParseDriverMode(ClangExecutable, ArgList.slice(1));
Hans Wennborg70850d82013-07-18 20:29:38 +0000568
Daniel Dunbar5e0f6af2009-03-13 00:51:18 +0000569 // FIXME: What are we going to do with -V and -b?
570
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +0000571 // FIXME: This stuff needs to go into the Compilation, not the driver.
Douglas Katzmanb7e8ef02015-06-25 19:37:41 +0000572 bool CCCPrintPhases;
Daniel Dunbard02cb1d2009-03-05 06:38:47 +0000573
David Blaikie69a1d8c2015-06-22 22:07:27 +0000574 InputArgList Args = ParseArgStrings(ArgList.slice(1));
Daniel Dunbaracd69572009-12-04 21:55:23 +0000575
Filipe Cabecinhas136f35e2015-07-18 06:35:24 +0000576 // Silence driver warnings if requested
577 Diags.setIgnoreAllWarnings(Args.hasArg(options::OPT_w));
578
Rafael Espindola59ae7992009-12-07 18:28:29 +0000579 // -no-canonical-prefixes is used very early in main.
David Blaikie69a1d8c2015-06-22 22:07:27 +0000580 Args.ClaimAllArgs(options::OPT_no_canonical_prefixes);
Rafael Espindola59ae7992009-12-07 18:28:29 +0000581
Daniel Dunbar926f81f2010-08-02 02:38:03 +0000582 // Ignore -pipe.
David Blaikie69a1d8c2015-06-22 22:07:27 +0000583 Args.ClaimAllArgs(options::OPT_pipe);
Daniel Dunbar926f81f2010-08-02 02:38:03 +0000584
Daniel Dunbaracd69572009-12-04 21:55:23 +0000585 // Extract -ccc args.
Daniel Dunbaree66cf22009-03-10 20:52:46 +0000586 //
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +0000587 // FIXME: We need to figure out where this behavior should live. Most of it
588 // should be outside in the client; the parts that aren't should have proper
589 // options, either by introducing new ones or by overloading gcc ones like -V
590 // or -b.
Douglas Katzmanb7e8ef02015-06-25 19:37:41 +0000591 CCCPrintPhases = Args.hasArg(options::OPT_ccc_print_phases);
David Blaikie69a1d8c2015-06-22 22:07:27 +0000592 CCCPrintBindings = Args.hasArg(options::OPT_ccc_print_bindings);
593 if (const Arg *A = Args.getLastArg(options::OPT_ccc_gcc_name))
Richard Smithbd55daf2012-11-01 04:30:05 +0000594 CCCGenericGCCName = A->getValue();
David Blaikie69a1d8c2015-06-22 22:07:27 +0000595 CCCUsePCH =
596 Args.hasFlag(options::OPT_ccc_pch_is_pch, options::OPT_ccc_pch_is_pth);
Joerg Sonnenberger17d75512012-02-22 19:15:16 +0000597 // FIXME: DefaultTargetTriple is used by the target-prefixed calls to as/ld
598 // and getToolChain is const.
Hans Wennborg2e274592013-08-13 23:38:57 +0000599 if (IsCLMode()) {
Hans Wennborg73609a02014-03-28 01:19:04 +0000600 // clang-cl targets MSVC-style Win32.
Hans Wennborg2e274592013-08-13 23:38:57 +0000601 llvm::Triple T(DefaultTargetTriple);
Hans Wennborg9d9ce7a2014-03-28 20:49:28 +0000602 T.setOS(llvm::Triple::Win32);
Hans Wennborg0f0e8d62015-09-18 17:11:50 +0000603 T.setVendor(llvm::Triple::PC);
Hans Wennborg9d9ce7a2014-03-28 20:49:28 +0000604 T.setEnvironment(llvm::Triple::MSVC);
Hans Wennborg2e274592013-08-13 23:38:57 +0000605 DefaultTargetTriple = T.str();
606 }
David Blaikie69a1d8c2015-06-22 22:07:27 +0000607 if (const Arg *A = Args.getLastArg(options::OPT_target))
Richard Smithbd55daf2012-11-01 04:30:05 +0000608 DefaultTargetTriple = A->getValue();
David Blaikie69a1d8c2015-06-22 22:07:27 +0000609 if (const Arg *A = Args.getLastArg(options::OPT_ccc_install_dir))
Richard Smithbd55daf2012-11-01 04:30:05 +0000610 Dir = InstalledDir = A->getValue();
David Blaikie69a1d8c2015-06-22 22:07:27 +0000611 for (const Arg *A : Args.filtered(options::OPT_B)) {
Benjamin Kramer1a648d12011-02-08 20:31:42 +0000612 A->claim();
Richard Smithbd55daf2012-11-01 04:30:05 +0000613 PrefixDirs.push_back(A->getValue(0));
Benjamin Kramer1a648d12011-02-08 20:31:42 +0000614 }
David Blaikie69a1d8c2015-06-22 22:07:27 +0000615 if (const Arg *A = Args.getLastArg(options::OPT__sysroot_EQ))
Richard Smithbd55daf2012-11-01 04:30:05 +0000616 SysRoot = A->getValue();
David Blaikie69a1d8c2015-06-22 22:07:27 +0000617 if (const Arg *A = Args.getLastArg(options::OPT__dyld_prefix_EQ))
Peter Collingbourne9d9e1fc2013-05-27 21:40:20 +0000618 DyldPrefix = A->getValue();
David Blaikie69a1d8c2015-06-22 22:07:27 +0000619 if (Args.hasArg(options::OPT_nostdlib))
Joerg Sonnenbergerbc923f32011-03-21 13:59:26 +0000620 UseStdLib = false;
Daniel Dunbaree66cf22009-03-10 20:52:46 +0000621
David Blaikie69a1d8c2015-06-22 22:07:27 +0000622 if (const Arg *A = Args.getLastArg(options::OPT_resource_dir))
Bob Wilsona20a1da2013-03-23 05:17:59 +0000623 ResourceDir = A->getValue();
Jim Grosbach061dabf2013-03-12 20:17:58 +0000624
David Blaikie69a1d8c2015-06-22 22:07:27 +0000625 if (const Arg *A = Args.getLastArg(options::OPT_save_temps_EQ)) {
Reid Kleckner68eb60b2015-02-02 22:41:48 +0000626 SaveTemps = llvm::StringSwitch<SaveTempsMode>(A->getValue())
627 .Case("cwd", SaveTempsCwd)
628 .Case("obj", SaveTempsObj)
629 .Default(SaveTempsCwd);
630 }
631
Steven Wu1257cd82016-05-18 17:04:52 +0000632 setLTOMode(Args);
633
Steven Wu844ab6a2016-11-16 06:06:44 +0000634 // Process -fembed-bitcode= flags.
635 if (Arg *A = Args.getLastArg(options::OPT_fembed_bitcode_EQ)) {
636 StringRef Name = A->getValue();
637 unsigned Model = llvm::StringSwitch<unsigned>(Name)
638 .Case("off", EmbedNone)
639 .Case("all", EmbedBitcode)
640 .Case("bitcode", EmbedBitcode)
641 .Case("marker", EmbedMarker)
642 .Default(~0U);
643 if (Model == ~0U) {
644 Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args)
645 << Name;
646 } else
647 BitcodeEmbed = static_cast<BitcodeEmbedMode>(Model);
Steven Wu574b0f22016-03-01 01:07:58 +0000648 }
649
David Blaikie69a1d8c2015-06-22 22:07:27 +0000650 std::unique_ptr<llvm::opt::InputArgList> UArgs =
651 llvm::make_unique<InputArgList>(std::move(Args));
652
Daniel Dunbar775d4062010-06-11 22:00:26 +0000653 // Perform the default argument translations.
David Blaikie69a1d8c2015-06-22 22:07:27 +0000654 DerivedArgList *TranslatedArgs = TranslateInputArgs(*UArgs);
Daniel Dunbar775d4062010-06-11 22:00:26 +0000655
Chandler Carruthcb916192012-01-25 08:49:21 +0000656 // Owned by the host.
Andrey Turetskiy6a8b91d2016-04-21 10:16:48 +0000657 const ToolChain &TC = getToolChain(
658 *UArgs, computeTargetTriple(*this, DefaultTargetTriple, *UArgs));
Chandler Carruthcb916192012-01-25 08:49:21 +0000659
Daniel Dunbar3ce436d2009-03-16 06:42:30 +0000660 // The compilation takes ownership of Args.
David Blaikie69a1d8c2015-06-22 22:07:27 +0000661 Compilation *C = new Compilation(*this, TC, UArgs.release(), TranslatedArgs);
Daniel Dunbarf0eddb82009-03-18 02:55:38 +0000662
Daniel Dunbarf0eddb82009-03-18 02:55:38 +0000663 if (!HandleImmediateArgs(*C))
664 return C;
665
Chad Rosierecdede82011-08-12 22:08:57 +0000666 // Construct the list of inputs.
667 InputList Inputs;
Hans Wennborged1d0722013-08-13 21:32:29 +0000668 BuildInputs(C->getDefaultToolChain(), *TranslatedArgs, Inputs);
Chad Rosierecdede82011-08-12 22:08:57 +0000669
Samuel Antaoc1ffba52016-06-13 18:10:57 +0000670 // Populate the tool chains for the offloading devices, if any.
671 CreateOffloadingDeviceToolChains(*C, Inputs);
Justin Lebar0e450a52016-03-30 23:30:25 +0000672
Chandler Carruth7f1417f2012-01-24 10:43:44 +0000673 // Construct the list of abstract actions to perform for this compilation. On
Tim Northover157d9112014-01-16 08:48:16 +0000674 // MachO targets this uses the driver-driver and universal actions.
675 if (TC.getTriple().isOSBinFormatMachO())
Artem Belevich5e2a3ec2015-11-17 22:28:40 +0000676 BuildUniversalActions(*C, C->getDefaultToolChain(), Inputs);
Daniel Dunbarf0eddb82009-03-18 02:55:38 +0000677 else
Justin Lebar0f3474c2016-02-11 02:00:50 +0000678 BuildActions(*C, C->getArgs(), Inputs, C->getActions());
Daniel Dunbarf0eddb82009-03-18 02:55:38 +0000679
Douglas Katzmanb7e8ef02015-06-25 19:37:41 +0000680 if (CCCPrintPhases) {
Daniel Dunbareb843be2009-03-18 03:13:20 +0000681 PrintActions(*C);
Daniel Dunbarf0eddb82009-03-18 02:55:38 +0000682 return C;
683 }
684
685 BuildJobs(*C);
Daniel Dunbaradc91e62009-03-15 01:38:15 +0000686
687 return C;
Daniel Dunbaree66cf22009-03-10 20:52:46 +0000688}
689
Justin Bognered9cbe02015-07-09 06:58:31 +0000690static void printArgList(raw_ostream &OS, const llvm::opt::ArgList &Args) {
691 llvm::opt::ArgStringList ASL;
692 for (const auto *A : Args)
693 A->render(Args, ASL);
694
695 for (auto I = ASL.begin(), E = ASL.end(); I != E; ++I) {
696 if (I != ASL.begin())
697 OS << ' ';
698 Command::printArg(OS, *I, true);
699 }
700 OS << '\n';
701}
702
Bruno Cardoso Lopes02681c42016-11-17 21:41:22 +0000703bool Driver::getCrashDiagnosticFile(StringRef ReproCrashFilename,
704 SmallString<128> &CrashDiagDir) {
705 using namespace llvm::sys;
706 assert(llvm::Triple(llvm::sys::getProcessTriple()).isOSDarwin() &&
707 "Only knows about .crash files on Darwin");
708
709 // The .crash file can be found on at ~/Library/Logs/DiagnosticReports/
710 // (or /Library/Logs/DiagnosticReports for root) and has the filename pattern
711 // clang-<VERSION>_<YYYY-MM-DD-HHMMSS>_<hostname>.crash.
712 path::home_directory(CrashDiagDir);
713 if (CrashDiagDir.startswith("/var/root"))
714 CrashDiagDir = "/";
715 path::append(CrashDiagDir, "Library/Logs/DiagnosticReports");
716 int PID =
717#if LLVM_ON_UNIX
718 getpid();
719#else
720 0;
721#endif
722 std::error_code EC;
723 fs::file_status FileStatus;
724 TimePoint<> LastAccessTime;
725 SmallString<128> CrashFilePath;
726 // Lookup the .crash files and get the one generated by a subprocess spawned
727 // by this driver invocation.
728 for (fs::directory_iterator File(CrashDiagDir, EC), FileEnd;
729 File != FileEnd && !EC; File.increment(EC)) {
730 StringRef FileName = path::filename(File->path());
731 if (!FileName.startswith(Name))
732 continue;
733 if (fs::status(File->path(), FileStatus))
734 continue;
735 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> CrashFile =
736 llvm::MemoryBuffer::getFile(File->path());
737 if (!CrashFile)
738 continue;
739 // The first line should start with "Process:", otherwise this isn't a real
740 // .crash file.
741 StringRef Data = CrashFile.get()->getBuffer();
742 if (!Data.startswith("Process:"))
743 continue;
744 // Parse parent process pid line, e.g: "Parent Process: clang-4.0 [79141]"
745 size_t ParentProcPos = Data.find("Parent Process:");
746 if (ParentProcPos == StringRef::npos)
747 continue;
748 size_t LineEnd = Data.find_first_of("\n", ParentProcPos);
749 if (LineEnd == StringRef::npos)
750 continue;
751 StringRef ParentProcess = Data.slice(ParentProcPos+15, LineEnd).trim();
752 int OpenBracket = -1, CloseBracket = -1;
753 for (size_t i = 0, e = ParentProcess.size(); i < e; ++i) {
754 if (ParentProcess[i] == '[')
755 OpenBracket = i;
756 if (ParentProcess[i] == ']')
757 CloseBracket = i;
758 }
759 // Extract the parent process PID from the .crash file and check whether
760 // it matches this driver invocation pid.
761 int CrashPID;
762 if (OpenBracket < 0 || CloseBracket < 0 ||
763 ParentProcess.slice(OpenBracket + 1, CloseBracket)
764 .getAsInteger(10, CrashPID) || CrashPID != PID) {
765 continue;
766 }
767
768 // Found a .crash file matching the driver pid. To avoid getting an older
769 // and misleading crash file, continue looking for the most recent.
770 // FIXME: the driver can dispatch multiple cc1 invocations, leading to
771 // multiple crashes poiting to the same parent process. Since the driver
772 // does not collect pid information for the dispatched invocation there's
773 // currently no way to distinguish among them.
774 const auto FileAccessTime = FileStatus.getLastModificationTime();
775 if (FileAccessTime > LastAccessTime) {
776 CrashFilePath.assign(File->path());
777 LastAccessTime = FileAccessTime;
778 }
779 }
780
781 // If found, copy it over to the location of other reproducer files.
782 if (!CrashFilePath.empty()) {
783 EC = fs::copy_file(CrashFilePath, ReproCrashFilename);
784 if (EC)
785 return false;
786 return true;
787 }
788
789 return false;
790}
791
Eric Christopherf901e852011-08-17 22:59:59 +0000792// When clang crashes, produce diagnostic information including the fully
793// preprocessed source file(s). Request that the developer attach the
Chad Rosierbe10f982011-08-02 17:58:04 +0000794// diagnostic information to a bug report.
795void Driver::generateCompilationDiagnostics(Compilation &C,
Justin Bognere1a33d12014-10-20 21:02:05 +0000796 const Command &FailingCommand) {
Chad Rosier877c0a22012-02-22 00:30:39 +0000797 if (C.getArgs().hasArg(options::OPT_fno_crash_diagnostics))
Chad Rosier62135492012-07-09 17:31:28 +0000798 return;
Chad Rosierbee5a1d2012-03-07 00:30:40 +0000799
Chad Rosierdbf46a12013-02-01 18:30:26 +0000800 // Don't try to generate diagnostics for link or dsymutil jobs.
Justin Bognere1a33d12014-10-20 21:02:05 +0000801 if (FailingCommand.getCreator().isLinkJob() ||
802 FailingCommand.getCreator().isDsymutilJob())
Chad Rosier877c0a22012-02-22 00:30:39 +0000803 return;
804
Chad Rosier8179f112012-06-19 17:51:34 +0000805 // Print the version of the compiler.
806 PrintVersion(C, llvm::errs());
807
Chad Rosierbe10f982011-08-02 17:58:04 +0000808 Diag(clang::diag::note_drv_command_failed_diag_msg)
Douglas Katzmana67e50c2015-06-26 15:47:46 +0000809 << "PLEASE submit a bug report to " BUG_REPORT_URL " and include the "
810 "crash backtrace, preprocessed source, and associated run script.";
Chad Rosierbe10f982011-08-02 17:58:04 +0000811
812 // Suppress driver output and emit preprocessor output to temp file.
Hans Wennborg70850d82013-07-18 20:29:38 +0000813 Mode = CPPMode;
Chad Rosierbe10f982011-08-02 17:58:04 +0000814 CCGenDiagnostics = true;
815
Chad Rosiercdb008d2011-11-02 21:29:05 +0000816 // Save the original job command(s).
Justin Bogner25645152014-10-21 17:24:44 +0000817 Command Cmd = FailingCommand;
Chad Rosiercdb008d2011-11-02 21:29:05 +0000818
Richard Smith5bb4cdf2012-12-20 02:22:15 +0000819 // Keep track of whether we produce any errors while trying to produce
820 // preprocessed sources.
821 DiagnosticErrorTrap Trap(Diags);
822
823 // Suppress tool output.
Chad Rosierbe10f982011-08-02 17:58:04 +0000824 C.initCompilationForDiagnostics();
Chad Rosierecdede82011-08-12 22:08:57 +0000825
826 // Construct the list of inputs.
827 InputList Inputs;
828 BuildInputs(C.getDefaultToolChain(), C.getArgs(), Inputs);
Chad Rosierbe10f982011-08-02 17:58:04 +0000829
Chad Rosier4f81fc22011-08-12 23:30:05 +0000830 for (InputList::iterator it = Inputs.begin(), ie = Inputs.end(); it != ie;) {
Chad Rosierd57133d2011-08-18 00:22:25 +0000831 bool IgnoreInput = false;
832
833 // Ignore input from stdin or any inputs that cannot be preprocessed.
Paul Robinsonf44157d2014-04-28 22:24:44 +0000834 // Check type first as not all linker inputs have a value.
Douglas Katzmana67e50c2015-06-26 15:47:46 +0000835 if (types::getPreprocessedType(it->first) == types::TY_INVALID) {
Paul Robinsonf44157d2014-04-28 22:24:44 +0000836 IgnoreInput = true;
837 } else if (!strcmp(it->second->getValue(), "-")) {
Chad Rosierd57133d2011-08-18 00:22:25 +0000838 Diag(clang::diag::note_drv_command_failed_diag_msg)
Douglas Katzmana67e50c2015-06-26 15:47:46 +0000839 << "Error generating preprocessed source(s) - "
840 "ignoring input from stdin.";
Chad Rosierd57133d2011-08-18 00:22:25 +0000841 IgnoreInput = true;
Chad Rosierd57133d2011-08-18 00:22:25 +0000842 }
843
844 if (IgnoreInput) {
Chad Rosier4f81fc22011-08-12 23:30:05 +0000845 it = Inputs.erase(it);
846 ie = Inputs.end();
Chad Rosier6fdf38b2011-08-17 23:08:45 +0000847 } else {
Chad Rosier4f81fc22011-08-12 23:30:05 +0000848 ++it;
Chad Rosier6fdf38b2011-08-17 23:08:45 +0000849 }
Chad Rosier4f81fc22011-08-12 23:30:05 +0000850 }
Chad Rosierd57133d2011-08-18 00:22:25 +0000851
Chad Rosierc5103c32013-01-29 23:57:10 +0000852 if (Inputs.empty()) {
853 Diag(clang::diag::note_drv_command_failed_diag_msg)
Douglas Katzmana67e50c2015-06-26 15:47:46 +0000854 << "Error generating preprocessed source(s) - "
855 "no preprocessable inputs.";
Chad Rosierc5103c32013-01-29 23:57:10 +0000856 return;
857 }
858
Chad Rosiere75ef402011-09-06 23:52:36 +0000859 // Don't attempt to generate preprocessed files if multiple -arch options are
Chad Rosier636d2832012-02-13 18:16:28 +0000860 // used, unless they're all duplicates.
861 llvm::StringSet<> ArchNames;
Saleem Abdulrasool688b6bc2014-12-29 19:01:36 +0000862 for (const Arg *A : C.getArgs()) {
Chad Rosiere75ef402011-09-06 23:52:36 +0000863 if (A->getOption().matches(options::OPT_arch)) {
Richard Smithbd55daf2012-11-01 04:30:05 +0000864 StringRef ArchName = A->getValue();
Chad Rosier636d2832012-02-13 18:16:28 +0000865 ArchNames.insert(ArchName);
Chad Rosiere75ef402011-09-06 23:52:36 +0000866 }
867 }
Chad Rosier636d2832012-02-13 18:16:28 +0000868 if (ArchNames.size() > 1) {
869 Diag(clang::diag::note_drv_command_failed_diag_msg)
Douglas Katzmana67e50c2015-06-26 15:47:46 +0000870 << "Error generating preprocessed source(s) - cannot generate "
871 "preprocessed source with multiple -arch options.";
Chad Rosier636d2832012-02-13 18:16:28 +0000872 return;
873 }
Chad Rosiere75ef402011-09-06 23:52:36 +0000874
Chandler Carruth7f1417f2012-01-24 10:43:44 +0000875 // Construct the list of abstract actions to perform for this compilation. On
876 // Darwin OSes this uses the driver-driver and builds universal actions.
Chandler Carruthcb916192012-01-25 08:49:21 +0000877 const ToolChain &TC = C.getDefaultToolChain();
Tim Northover157d9112014-01-16 08:48:16 +0000878 if (TC.getTriple().isOSBinFormatMachO())
Artem Belevich5e2a3ec2015-11-17 22:28:40 +0000879 BuildUniversalActions(C, TC, Inputs);
Chad Rosierbe10f982011-08-02 17:58:04 +0000880 else
Justin Lebar0f3474c2016-02-11 02:00:50 +0000881 BuildActions(C, C.getArgs(), Inputs, C.getActions());
Chad Rosierbe10f982011-08-02 17:58:04 +0000882
883 BuildJobs(C);
884
885 // If there were errors building the compilation, quit now.
Richard Smith5bb4cdf2012-12-20 02:22:15 +0000886 if (Trap.hasErrorOccurred()) {
Chad Rosierbe10f982011-08-02 17:58:04 +0000887 Diag(clang::diag::note_drv_command_failed_diag_msg)
Douglas Katzmana67e50c2015-06-26 15:47:46 +0000888 << "Error generating preprocessed source(s).";
Chad Rosierbe10f982011-08-02 17:58:04 +0000889 return;
890 }
891
892 // Generate preprocessed output.
Chad Rosierdd60e092013-01-29 20:15:05 +0000893 SmallVector<std::pair<int, const Command *>, 4> FailingCommands;
Justin Bogner0cd92482015-07-02 22:52:08 +0000894 C.ExecuteJobs(C.getJobs(), FailingCommands);
Chad Rosierbe10f982011-08-02 17:58:04 +0000895
Justin Bognerbc89b182014-10-20 21:20:27 +0000896 // If any of the preprocessing commands failed, clean up and exit.
897 if (!FailingCommands.empty()) {
Reid Kleckner68eb60b2015-02-02 22:41:48 +0000898 if (!isSaveTempsEnabled())
Chad Rosierbe10f982011-08-02 17:58:04 +0000899 C.CleanupFileList(C.getTempFiles(), true);
900
901 Diag(clang::diag::note_drv_command_failed_diag_msg)
Douglas Katzmana67e50c2015-06-26 15:47:46 +0000902 << "Error generating preprocessed source(s).";
Justin Bognerbc89b182014-10-20 21:20:27 +0000903 return;
Chad Rosierbe10f982011-08-02 17:58:04 +0000904 }
Justin Bognerbc89b182014-10-20 21:20:27 +0000905
Justin Bognerc1fdf7f2014-10-20 21:47:56 +0000906 const ArgStringList &TempFiles = C.getTempFiles();
907 if (TempFiles.empty()) {
908 Diag(clang::diag::note_drv_command_failed_diag_msg)
Douglas Katzmana67e50c2015-06-26 15:47:46 +0000909 << "Error generating preprocessed source(s).";
Justin Bognerc1fdf7f2014-10-20 21:47:56 +0000910 return;
911 }
912
Justin Bognerbc89b182014-10-20 21:20:27 +0000913 Diag(clang::diag::note_drv_command_failed_diag_msg)
914 << "\n********************\n\n"
915 "PLEASE ATTACH THE FOLLOWING FILES TO THE BUG REPORT:\n"
916 "Preprocessed source(s) and associated run script(s) are located at:";
Justin Bognerbc89b182014-10-20 21:20:27 +0000917
Justin Bogner659ecc32014-10-20 22:47:23 +0000918 SmallString<128> VFS;
Bruno Cardoso Lopes02681c42016-11-17 21:41:22 +0000919 SmallString<128> ReproCrashFilename;
Justin Bogner659ecc32014-10-20 22:47:23 +0000920 for (const char *TempFile : TempFiles) {
Justin Bognerc1fdf7f2014-10-20 21:47:56 +0000921 Diag(clang::diag::note_drv_command_failed_diag_msg) << TempFile;
Bruno Cardoso Lopes02681c42016-11-17 21:41:22 +0000922 if (ReproCrashFilename.empty()) {
923 ReproCrashFilename = TempFile;
924 llvm::sys::path::replace_extension(ReproCrashFilename, ".crash");
925 }
Justin Bogner659ecc32014-10-20 22:47:23 +0000926 if (StringRef(TempFile).endswith(".cache")) {
927 // In some cases (modules) we'll dump extra data to help with reproducing
928 // the crash into a directory next to the output.
929 VFS = llvm::sys::path::filename(TempFile);
930 llvm::sys::path::append(VFS, "vfs", "vfs.yaml");
931 }
932 }
Justin Bognerc1fdf7f2014-10-20 21:47:56 +0000933
934 // Assume associated files are based off of the first temporary file.
Justin Bogner25645152014-10-21 17:24:44 +0000935 CrashReportInfo CrashInfo(TempFiles[0], VFS);
Justin Bognerc1fdf7f2014-10-20 21:47:56 +0000936
Justin Bogner25645152014-10-21 17:24:44 +0000937 std::string Script = CrashInfo.Filename.rsplit('.').first.str() + ".sh";
Justin Bognerc1fdf7f2014-10-20 21:47:56 +0000938 std::error_code EC;
Justin Bognerc1fdf7f2014-10-20 21:47:56 +0000939 llvm::raw_fd_ostream ScriptOS(Script, EC, llvm::sys::fs::F_Excl);
940 if (EC) {
941 Diag(clang::diag::note_drv_command_failed_diag_msg)
942 << "Error generating run script: " + Script + " " + EC.message();
943 } else {
Justin Bogner42220ed2015-03-12 00:14:35 +0000944 ScriptOS << "# Crash reproducer for " << getClangFullVersion() << "\n"
Justin Bognered9cbe02015-07-09 06:58:31 +0000945 << "# Driver args: ";
946 printArgList(ScriptOS, C.getInputArgs());
947 ScriptOS << "# Original command: ";
Justin Bogner42220ed2015-03-12 00:14:35 +0000948 Cmd.Print(ScriptOS, "\n", /*Quote=*/true);
Justin Bogner33bdbc62014-10-21 18:03:08 +0000949 Cmd.Print(ScriptOS, "\n", /*Quote=*/true, &CrashInfo);
Justin Bognerc1fdf7f2014-10-20 21:47:56 +0000950 Diag(clang::diag::note_drv_command_failed_diag_msg) << Script;
Justin Bognerbc89b182014-10-20 21:20:27 +0000951 }
Saleem Abdulrasool3661a822015-01-12 02:33:09 +0000952
Bruno Cardoso Lopes02681c42016-11-17 21:41:22 +0000953 // On darwin, provide information about the .crash diagnostic report.
954 if (llvm::Triple(llvm::sys::getProcessTriple()).isOSDarwin()) {
955 SmallString<128> CrashDiagDir;
956 if (getCrashDiagnosticFile(ReproCrashFilename, CrashDiagDir)) {
957 Diag(clang::diag::note_drv_command_failed_diag_msg)
958 << ReproCrashFilename.str();
959 } else { // Suggest a directory for the user to look for .crash files.
960 llvm::sys::path::append(CrashDiagDir, Name);
961 CrashDiagDir += "_<YYYY-MM-DD-HHMMSS>_<hostname>.crash";
962 Diag(clang::diag::note_drv_command_failed_diag_msg)
963 << "Crash backtrace is located in";
964 Diag(clang::diag::note_drv_command_failed_diag_msg)
965 << CrashDiagDir.str();
966 Diag(clang::diag::note_drv_command_failed_diag_msg)
967 << "(choose the .crash file that corresponds to your crash)";
968 }
969 }
970
Saleem Abdulrasool3661a822015-01-12 02:33:09 +0000971 for (const auto &A : C.getArgs().filtered(options::OPT_frewrite_map_file,
972 options::OPT_frewrite_map_file_EQ))
973 Diag(clang::diag::note_drv_command_failed_diag_msg) << A->getValue();
974
Justin Bognerbc89b182014-10-20 21:20:27 +0000975 Diag(clang::diag::note_drv_command_failed_diag_msg)
976 << "\n\n********************";
Chad Rosierbe10f982011-08-02 17:58:04 +0000977}
978
Justin Bogner0cd92482015-07-02 22:52:08 +0000979void Driver::setUpResponseFiles(Compilation &C, Command &Cmd) {
Oleg Ranevskyycd516372016-01-05 19:54:39 +0000980 // Since commandLineFitsWithinSystemLimits() may underestimate system's capacity
Reid Kleckner0290c9c2014-09-15 17:45:39 +0000981 // if the tool does not support response files, there is a chance/ that things
982 // will just work without a response file, so we silently just skip it.
Justin Bogner0cd92482015-07-02 22:52:08 +0000983 if (Cmd.getCreator().getResponseFilesSupport() == Tool::RF_None ||
Oleg Ranevskyycd516372016-01-05 19:54:39 +0000984 llvm::sys::commandLineFitsWithinSystemLimits(Cmd.getExecutable(), Cmd.getArguments()))
Reid Kleckner0290c9c2014-09-15 17:45:39 +0000985 return;
986
987 std::string TmpName = GetTemporaryPath("response", "txt");
Malcolm Parsonsf76f6502016-11-02 10:39:27 +0000988 Cmd.setResponseFile(C.addTempFile(C.getArgs().MakeArgString(TmpName)));
Reid Kleckner0290c9c2014-09-15 17:45:39 +0000989}
990
Douglas Katzmana67e50c2015-06-26 15:47:46 +0000991int Driver::ExecuteCompilation(
992 Compilation &C,
993 SmallVectorImpl<std::pair<int, const Command *>> &FailingCommands) {
Daniel Dunbar38bfda62009-07-01 20:03:04 +0000994 // Just print if -### was present.
995 if (C.getArgs().hasArg(options::OPT__HASH_HASH_HASH)) {
Hans Wennborgb212b342013-09-12 18:23:34 +0000996 C.getJobs().Print(llvm::errs(), "\n", true);
Daniel Dunbar38bfda62009-07-01 20:03:04 +0000997 return 0;
998 }
999
1000 // If there were errors building the compilation, quit now.
Chad Rosierbe10f982011-08-02 17:58:04 +00001001 if (Diags.hasErrorOccurred())
Daniel Dunbar38bfda62009-07-01 20:03:04 +00001002 return 1;
1003
Reid Kleckner0290c9c2014-09-15 17:45:39 +00001004 // Set up response file names for each command, if necessary
Justin Bogner0cd92482015-07-02 22:52:08 +00001005 for (auto &Job : C.getJobs())
1006 setUpResponseFiles(C, Job);
Reid Kleckner0290c9c2014-09-15 17:45:39 +00001007
Justin Bogner0cd92482015-07-02 22:52:08 +00001008 C.ExecuteJobs(C.getJobs(), FailingCommands);
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001009
Daniel Dunbar38bfda62009-07-01 20:03:04 +00001010 // Remove temp files.
1011 C.CleanupFileList(C.getTempFiles());
1012
Daniel Dunbar07494792010-05-22 00:37:20 +00001013 // If the command succeeded, we are done.
Chad Rosierdd60e092013-01-29 20:15:05 +00001014 if (FailingCommands.empty())
1015 return 0;
Daniel Dunbar07494792010-05-22 00:37:20 +00001016
Chad Rosierdd60e092013-01-29 20:15:05 +00001017 // Otherwise, remove result files and print extra information about abnormal
1018 // failures.
Douglas Katzman6bbffc42015-06-25 18:51:37 +00001019 for (const auto &CmdPair : FailingCommands) {
1020 int Res = CmdPair.first;
1021 const Command *FailingCommand = CmdPair.second;
Daniel Dunbar38bfda62009-07-01 20:03:04 +00001022
Chad Rosierdd60e092013-01-29 20:15:05 +00001023 // Remove result files if we're not saving temps.
Reid Kleckner68eb60b2015-02-02 22:41:48 +00001024 if (!isSaveTempsEnabled()) {
Chad Rosierdd60e092013-01-29 20:15:05 +00001025 const JobAction *JA = cast<JobAction>(&FailingCommand->getSource());
1026 C.CleanupFileMap(C.getResultFiles(), JA, true);
1027
1028 // Failure result files are valid unless we crashed.
1029 if (Res < 0)
1030 C.CleanupFileMap(C.getFailureResultFiles(), JA, true);
1031 }
1032
1033 // Print extra information about abnormal failures, if possible.
1034 //
1035 // This is ad-hoc, but we don't want to be excessively noisy. If the result
Justin Bogner5aaf2e72014-06-26 20:59:36 +00001036 // status was 1, assume the command failed normally. In particular, if it
Chad Rosierdd60e092013-01-29 20:15:05 +00001037 // was the compiler then assume it gave a reasonable error code. Failures
1038 // in other tools are less common, and they generally have worse
1039 // diagnostics, so always print the diagnostic there.
1040 const Tool &FailingTool = FailingCommand->getCreator();
1041
1042 if (!FailingCommand->getCreator().hasGoodDiagnostics() || Res != 1) {
1043 // FIXME: See FIXME above regarding result code interpretation.
1044 if (Res < 0)
1045 Diag(clang::diag::err_drv_command_signalled)
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001046 << FailingTool.getShortName();
Chad Rosierdd60e092013-01-29 20:15:05 +00001047 else
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001048 Diag(clang::diag::err_drv_command_failed) << FailingTool.getShortName()
1049 << Res;
Chad Rosierdd60e092013-01-29 20:15:05 +00001050 }
Peter Collingbourne119cfaa2011-11-21 00:01:05 +00001051 }
Chad Rosierdd60e092013-01-29 20:15:05 +00001052 return 0;
Daniel Dunbar38bfda62009-07-01 20:03:04 +00001053}
1054
Daniel Dunbara7b5e212009-04-15 16:34:29 +00001055void Driver::PrintHelp(bool ShowHidden) const {
Hans Wennborg6ddc6902013-07-27 00:23:45 +00001056 unsigned IncludedFlagsBitmask;
1057 unsigned ExcludedFlagsBitmask;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00001058 std::tie(IncludedFlagsBitmask, ExcludedFlagsBitmask) =
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001059 getIncludeExcludeOptionFlagMasks();
Hans Wennborg6ddc6902013-07-27 00:23:45 +00001060
1061 ExcludedFlagsBitmask |= options::NoDriverOption;
1062 if (!ShowHidden)
1063 ExcludedFlagsBitmask |= HelpHidden;
1064
1065 getOpts().PrintHelp(llvm::outs(), Name.c_str(), DriverTitle.c_str(),
1066 IncludedFlagsBitmask, ExcludedFlagsBitmask);
Daniel Dunbar7c925282009-03-31 21:38:17 +00001067}
1068
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001069void Driver::PrintVersion(const Compilation &C, raw_ostream &OS) const {
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001070 // FIXME: The following handlers should use a callback mechanism, we don't
1071 // know what the client would like to do.
Ted Kremenek4c0df3d2010-01-23 02:11:34 +00001072 OS << getClangFullVersion() << '\n';
Daniel Dunbarb10248802009-03-26 16:09:13 +00001073 const ToolChain &TC = C.getDefaultToolChain();
Daniel Dunbar08e41d62009-07-21 20:06:58 +00001074 OS << "Target: " << TC.getTripleString() << '\n';
Daniel Dunbar10978e42009-06-16 23:32:58 +00001075
1076 // Print the threading model.
Jonathan Roelofsb140a102014-10-03 21:57:44 +00001077 if (Arg *A = C.getArgs().getLastArg(options::OPT_mthread_model)) {
1078 // Don't print if the ToolChain would have barfed on it already
1079 if (TC.isThreadModelSupported(A->getValue()))
1080 OS << "Thread model: " << A->getValue();
1081 } else
1082 OS << "Thread model: " << TC.getThreadModel();
1083 OS << '\n';
Chandler Carruth9ade6a92015-08-05 17:07:33 +00001084
1085 // Print out the install directory.
1086 OS << "InstalledDir: " << InstalledDir << '\n';
Daniel Dunbar5e0f6af2009-03-13 00:51:18 +00001087}
1088
Chris Lattner86ed5b02010-05-05 05:53:24 +00001089/// PrintDiagnosticCategories - Implement the --print-diagnostic-categories
1090/// option.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001091static void PrintDiagnosticCategories(raw_ostream &OS) {
Argyrios Kyrtzidis0e37afa2011-05-25 05:05:01 +00001092 // Skip the empty category.
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001093 for (unsigned i = 1, max = DiagnosticIDs::getNumberOfCategories(); i != max;
1094 ++i)
Argyrios Kyrtzidis0e37afa2011-05-25 05:05:01 +00001095 OS << i << ',' << DiagnosticIDs::getCategoryNameFromID(i) << '\n';
Chris Lattner86ed5b02010-05-05 05:53:24 +00001096}
1097
Daniel Dunbarf0eddb82009-03-18 02:55:38 +00001098bool Driver::HandleImmediateArgs(const Compilation &C) {
Daniel Dunbar18974bd2010-06-11 22:00:19 +00001099 // The order these options are handled in gcc is all over the place, but we
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001100 // don't expect inconsistencies w.r.t. that to matter in practice.
Daniel Dunbar7c925282009-03-31 21:38:17 +00001101
Daniel Dunbar1b09e042010-09-17 02:47:28 +00001102 if (C.getArgs().hasArg(options::OPT_dumpmachine)) {
1103 llvm::outs() << C.getDefaultToolChain().getTripleString() << '\n';
1104 return false;
1105 }
1106
Daniel Dunbara9bbcfa2009-04-04 05:17:38 +00001107 if (C.getArgs().hasArg(options::OPT_dumpversion)) {
Daniel Dunbare26e5002011-01-12 00:43:47 +00001108 // Since -dumpversion is only implemented for pedantic GCC compatibility, we
1109 // return an answer which matches our definition of __VERSION__.
1110 //
1111 // If we want to return a more correct answer some day, then we should
1112 // introduce a non-pedantically GCC compatible mode to Clang in which we
1113 // provide sensible definitions for -dumpversion, __VERSION__, etc.
1114 llvm::outs() << "4.2.1\n";
Daniel Dunbara9bbcfa2009-04-04 05:17:38 +00001115 return false;
1116 }
Daniel Dunbarfb3d7472010-06-14 21:23:12 +00001117
Chris Lattner86ed5b02010-05-05 05:53:24 +00001118 if (C.getArgs().hasArg(options::OPT__print_diagnostic_categories)) {
1119 PrintDiagnosticCategories(llvm::outs());
1120 return false;
1121 }
Daniel Dunbara9bbcfa2009-04-04 05:17:38 +00001122
James Molloya3c85b82012-05-01 14:57:16 +00001123 if (C.getArgs().hasArg(options::OPT_help) ||
Daniel Dunbara7b5e212009-04-15 16:34:29 +00001124 C.getArgs().hasArg(options::OPT__help_hidden)) {
1125 PrintHelp(C.getArgs().hasArg(options::OPT__help_hidden));
Daniel Dunbar7c925282009-03-31 21:38:17 +00001126 return false;
1127 }
1128
Daniel Dunbarb0006ae2009-04-02 15:05:41 +00001129 if (C.getArgs().hasArg(options::OPT__version)) {
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001130 // Follow gcc behavior and use stdout for --version and stderr for -v.
Daniel Dunbar08e41d62009-07-21 20:06:58 +00001131 PrintVersion(C, llvm::outs());
Daniel Dunbarb0006ae2009-04-02 15:05:41 +00001132 return false;
1133 }
1134
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001135 if (C.getArgs().hasArg(options::OPT_v) ||
Daniel Dunbarf0eddb82009-03-18 02:55:38 +00001136 C.getArgs().hasArg(options::OPT__HASH_HASH_HASH)) {
Daniel Dunbar08e41d62009-07-21 20:06:58 +00001137 PrintVersion(C, llvm::errs());
Daniel Dunbar5e0f6af2009-03-13 00:51:18 +00001138 SuppressMissingInputWarning = true;
1139 }
1140
Daniel Dunbarf0eddb82009-03-18 02:55:38 +00001141 const ToolChain &TC = C.getDefaultToolChain();
Chandler Carruth0ae39aa2013-07-30 17:57:09 +00001142
1143 if (C.getArgs().hasArg(options::OPT_v))
1144 TC.printVerboseInfo(llvm::errs());
1145
Daniel Dunbard972e222009-03-20 04:37:21 +00001146 if (C.getArgs().hasArg(options::OPT_print_search_dirs)) {
1147 llvm::outs() << "programs: =";
Douglas Katzman51fe7bf2015-06-23 22:43:50 +00001148 bool separator = false;
1149 for (const std::string &Path : TC.getProgramPaths()) {
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001150 if (separator)
1151 llvm::outs() << ':';
Douglas Katzman51fe7bf2015-06-23 22:43:50 +00001152 llvm::outs() << Path;
1153 separator = true;
Daniel Dunbard972e222009-03-20 04:37:21 +00001154 }
1155 llvm::outs() << "\n";
Peter Collingbournefa9771f2011-09-06 02:08:31 +00001156 llvm::outs() << "libraries: =" << ResourceDir;
Joerg Sonnenberger9c3e69b2011-07-16 10:50:05 +00001157
Sebastian Pop980920a2012-04-16 04:16:43 +00001158 StringRef sysroot = C.getSysRoot();
Joerg Sonnenberger9c3e69b2011-07-16 10:50:05 +00001159
Douglas Katzman51fe7bf2015-06-23 22:43:50 +00001160 for (const std::string &Path : TC.getFilePaths()) {
1161 // Always print a separator. ResourceDir was the first item shown.
Peter Collingbournefa9771f2011-09-06 02:08:31 +00001162 llvm::outs() << ':';
Douglas Katzman51fe7bf2015-06-23 22:43:50 +00001163 // Interpretation of leading '=' is needed only for NetBSD.
1164 if (Path[0] == '=')
Douglas Katzman26eabf62015-06-24 15:10:30 +00001165 llvm::outs() << sysroot << Path.substr(1);
Joerg Sonnenberger9c3e69b2011-07-16 10:50:05 +00001166 else
Douglas Katzman51fe7bf2015-06-23 22:43:50 +00001167 llvm::outs() << Path;
Daniel Dunbard972e222009-03-20 04:37:21 +00001168 }
1169 llvm::outs() << "\n";
Daniel Dunbar7c925282009-03-31 21:38:17 +00001170 return false;
Daniel Dunbard972e222009-03-20 04:37:21 +00001171 }
1172
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001173 // FIXME: The following handlers should use a callback mechanism, we don't
1174 // know what the client would like to do.
Daniel Dunbarf0eddb82009-03-18 02:55:38 +00001175 if (Arg *A = C.getArgs().getLastArg(options::OPT_print_file_name_EQ)) {
Richard Smithbd55daf2012-11-01 04:30:05 +00001176 llvm::outs() << GetFilePath(A->getValue(), TC) << "\n";
Daniel Dunbar5e0f6af2009-03-13 00:51:18 +00001177 return false;
1178 }
1179
Daniel Dunbarf0eddb82009-03-18 02:55:38 +00001180 if (Arg *A = C.getArgs().getLastArg(options::OPT_print_prog_name_EQ)) {
Richard Smithbd55daf2012-11-01 04:30:05 +00001181 llvm::outs() << GetProgramPath(A->getValue(), TC) << "\n";
Daniel Dunbar5e0f6af2009-03-13 00:51:18 +00001182 return false;
1183 }
1184
Daniel Dunbarf0eddb82009-03-18 02:55:38 +00001185 if (C.getArgs().hasArg(options::OPT_print_libgcc_file_name)) {
Michal Gorny7cfe4802016-10-10 12:23:40 +00001186 ToolChain::RuntimeLibType RLT = TC.GetRuntimeLibType(C.getArgs());
1187 switch (RLT) {
1188 case ToolChain::RLT_CompilerRT:
1189 llvm::outs() << TC.getCompilerRT(C.getArgs(), "builtins") << "\n";
1190 break;
1191 case ToolChain::RLT_Libgcc:
1192 llvm::outs() << GetFilePath("libgcc.a", TC) << "\n";
1193 break;
1194 }
Daniel Dunbar5e0f6af2009-03-13 00:51:18 +00001195 return false;
1196 }
1197
Daniel Dunbar1b3ec3a2009-06-16 23:25:22 +00001198 if (C.getArgs().hasArg(options::OPT_print_multi_lib)) {
Douglas Katzmana34b7bf2015-06-30 19:32:57 +00001199 for (const Multilib &Multilib : TC.getMultilibs())
1200 llvm::outs() << Multilib << "\n";
Daniel Dunbar1b3ec3a2009-06-16 23:25:22 +00001201 return false;
1202 }
1203
Jonathan Roelofs2cea1be2014-02-12 03:21:20 +00001204 if (C.getArgs().hasArg(options::OPT_print_multi_directory)) {
Douglas Katzmana34b7bf2015-06-30 19:32:57 +00001205 for (const Multilib &Multilib : TC.getMultilibs()) {
Douglas Katzman6bbffc42015-06-25 18:51:37 +00001206 if (Multilib.gccSuffix().empty())
Jonathan Roelofs2cea1be2014-02-12 03:21:20 +00001207 llvm::outs() << ".\n";
1208 else {
Douglas Katzman6bbffc42015-06-25 18:51:37 +00001209 StringRef Suffix(Multilib.gccSuffix());
Jonathan Roelofs2cea1be2014-02-12 03:21:20 +00001210 assert(Suffix.front() == '/');
1211 llvm::outs() << Suffix.substr(1) << "\n";
1212 }
Jonathan Roelofs3fa96d82014-02-12 01:36:51 +00001213 }
Jonathan Roelofs0e7ec602014-02-12 01:29:25 +00001214 return false;
1215 }
Daniel Dunbar5e0f6af2009-03-13 00:51:18 +00001216 return true;
1217}
1218
Douglas Katzmanfd528672015-06-11 15:05:22 +00001219// Display an action graph human-readably. Action A is the "sink" node
1220// and latest-occuring action. Traversal is in pre-order, visiting the
1221// inputs to each action before printing the action itself.
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001222static unsigned PrintActions1(const Compilation &C, Action *A,
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001223 std::map<Action *, unsigned> &Ids) {
Douglas Katzmanfd528672015-06-11 15:05:22 +00001224 if (Ids.count(A)) // A was already visited.
Daniel Dunbaraaf1ea62009-03-13 12:19:02 +00001225 return Ids[A];
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001226
Daniel Dunbaraaf1ea62009-03-13 12:19:02 +00001227 std::string str;
1228 llvm::raw_string_ostream os(str);
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001229
Daniel Dunbaraaf1ea62009-03-13 12:19:02 +00001230 os << Action::getClassName(A->getKind()) << ", ";
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001231 if (InputAction *IA = dyn_cast<InputAction>(A)) {
Richard Smithbd55daf2012-11-01 04:30:05 +00001232 os << "\"" << IA->getInputArg().getValue() << "\"";
Daniel Dunbaraaf1ea62009-03-13 12:19:02 +00001233 } else if (BindArchAction *BIA = dyn_cast<BindArchAction>(A)) {
Douglas Katzmanb7e8ef02015-06-25 19:37:41 +00001234 os << '"' << BIA->getArchName() << '"' << ", {"
Nico Weber5a459f82016-02-23 19:30:43 +00001235 << PrintActions1(C, *BIA->input_begin(), Ids) << "}";
Samuel Antaod06239d2016-07-15 23:13:27 +00001236 } else if (OffloadAction *OA = dyn_cast<OffloadAction>(A)) {
1237 bool IsFirst = true;
1238 OA->doOnEachDependence(
1239 [&](Action *A, const ToolChain *TC, const char *BoundArch) {
1240 // E.g. for two CUDA device dependences whose bound arch is sm_20 and
1241 // sm_35 this will generate:
1242 // "cuda-device" (nvptx64-nvidia-cuda:sm_20) {#ID}, "cuda-device"
1243 // (nvptx64-nvidia-cuda:sm_35) {#ID}
1244 if (!IsFirst)
1245 os << ", ";
1246 os << '"';
1247 if (TC)
1248 os << A->getOffloadingKindPrefix();
1249 else
1250 os << "host";
1251 os << " (";
1252 os << TC->getTriple().normalize();
1253
1254 if (BoundArch)
1255 os << ":" << BoundArch;
1256 os << ")";
1257 os << '"';
1258 os << " {" << PrintActions1(C, A, Ids) << "}";
1259 IsFirst = false;
1260 });
Daniel Dunbaraaf1ea62009-03-13 12:19:02 +00001261 } else {
Samuel Antaod06239d2016-07-15 23:13:27 +00001262 const ActionList *AL = &A->getInputs();
Artem Belevich0ff05cd2015-07-13 23:27:56 +00001263
Artem Belevich23256752015-09-22 17:23:09 +00001264 if (AL->size()) {
1265 const char *Prefix = "{";
1266 for (Action *PreRequisite : *AL) {
1267 os << Prefix << PrintActions1(C, PreRequisite, Ids);
1268 Prefix = ", ";
1269 }
1270 os << "}";
1271 } else
1272 os << "{}";
Daniel Dunbaraaf1ea62009-03-13 12:19:02 +00001273 }
1274
Samuel Antaod06239d2016-07-15 23:13:27 +00001275 // Append offload info for all options other than the offloading action
1276 // itself (e.g. (cuda-device, sm_20) or (cuda-host)).
1277 std::string offload_str;
1278 llvm::raw_string_ostream offload_os(offload_str);
1279 if (!isa<OffloadAction>(A)) {
1280 auto S = A->getOffloadingKindPrefix();
1281 if (!S.empty()) {
1282 offload_os << ", (" << S;
1283 if (A->getOffloadingArch())
1284 offload_os << ", " << A->getOffloadingArch();
1285 offload_os << ")";
1286 }
1287 }
1288
Daniel Dunbaraaf1ea62009-03-13 12:19:02 +00001289 unsigned Id = Ids.size();
1290 Ids[A] = Id;
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001291 llvm::errs() << Id << ": " << os.str() << ", "
Samuel Antaod06239d2016-07-15 23:13:27 +00001292 << types::getTypeName(A->getType()) << offload_os.str() << "\n";
Daniel Dunbaraaf1ea62009-03-13 12:19:02 +00001293
1294 return Id;
1295}
1296
Douglas Katzmanfd528672015-06-11 15:05:22 +00001297// Print the action graphs in a compilation C.
1298// For example "clang -c file1.c file2.c" is composed of two subgraphs.
Daniel Dunbareb843be2009-03-18 03:13:20 +00001299void Driver::PrintActions(const Compilation &C) const {
Douglas Katzmanb7e8ef02015-06-25 19:37:41 +00001300 std::map<Action *, unsigned> Ids;
1301 for (Action *A : C.getActions())
1302 PrintActions1(C, A, Ids);
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00001303}
1304
Joerg Sonnenberger5fe4a7d2011-05-06 14:05:11 +00001305/// \brief Check whether the given input tree contains any compilation or
1306/// assembly actions.
1307static bool ContainsCompileOrAssembleAction(const Action *A) {
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001308 if (isa<CompileJobAction>(A) || isa<BackendJobAction>(A) ||
Bob Wilson23a55f12014-12-21 07:00:00 +00001309 isa<AssembleJobAction>(A))
Daniel Dunbar00d3d8e2010-06-29 16:38:33 +00001310 return true;
1311
Nico Weber5a459f82016-02-23 19:30:43 +00001312 for (const Action *Input : A->inputs())
Nico Weberfb80f962015-09-19 21:36:51 +00001313 if (ContainsCompileOrAssembleAction(Input))
Daniel Dunbar00d3d8e2010-06-29 16:38:33 +00001314 return true;
1315
1316 return false;
1317}
1318
Artem Belevich5e2a3ec2015-11-17 22:28:40 +00001319void Driver::BuildUniversalActions(Compilation &C, const ToolChain &TC,
1320 const InputList &BAInputs) const {
1321 DerivedArgList &Args = C.getArgs();
1322 ActionList &Actions = C.getActions();
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001323 llvm::PrettyStackTraceString CrashInfo("Building universal build actions");
1324 // Collect the list of architectures. Duplicates are allowed, but should only
1325 // be handled once (in the order seen).
Daniel Dunbare5dc4822009-03-13 20:33:35 +00001326 llvm::StringSet<> ArchNames;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001327 SmallVector<const char *, 4> Archs;
Saleem Abdulrasool688b6bc2014-12-29 19:01:36 +00001328 for (Arg *A : Args) {
Daniel Dunbar0bfb21e2009-11-19 03:26:40 +00001329 if (A->getOption().matches(options::OPT_arch)) {
Daniel Dunbar9c3f7c42009-09-08 23:37:30 +00001330 // Validate the option here; we don't save the type here because its
1331 // particular spelling may participate in other driver choices.
1332 llvm::Triple::ArchType Arch =
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001333 tools::darwin::getArchTypeForMachOArchName(A->getValue());
Daniel Dunbar9c3f7c42009-09-08 23:37:30 +00001334 if (Arch == llvm::Triple::UnknownArch) {
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001335 Diag(clang::diag::err_drv_invalid_arch_name) << A->getAsString(Args);
Daniel Dunbar9c3f7c42009-09-08 23:37:30 +00001336 continue;
1337 }
1338
Daniel Dunbar2da02722009-03-19 07:55:12 +00001339 A->claim();
David Blaikie61b86d42014-11-19 02:56:13 +00001340 if (ArchNames.insert(A->getValue()).second)
Richard Smithbd55daf2012-11-01 04:30:05 +00001341 Archs.push_back(A->getValue());
Daniel Dunbarf479c122009-03-12 18:40:18 +00001342 }
1343 }
1344
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001345 // When there is no explicit arch for this platform, make sure we still bind
1346 // the architecture (to the default) so that -Xarch_ is handled correctly.
Daniel Dunbareb843be2009-03-18 03:13:20 +00001347 if (!Archs.size())
Daniel Dunbarc3bd9f52012-11-08 03:38:26 +00001348 Archs.push_back(Args.MakeArgString(TC.getDefaultUniversalArchName()));
Daniel Dunbarf479c122009-03-12 18:40:18 +00001349
Daniel Dunbarf479c122009-03-12 18:40:18 +00001350 ActionList SingleActions;
Justin Lebar0f3474c2016-02-11 02:00:50 +00001351 BuildActions(C, Args, BAInputs, SingleActions);
Daniel Dunbarf479c122009-03-12 18:40:18 +00001352
Daniel Dunbar6beaf512010-06-04 18:28:41 +00001353 // Add in arch bindings for every top level action, as well as lipo and
1354 // dsymutil steps if needed.
Nico Weberfb80f962015-09-19 21:36:51 +00001355 for (Action* Act : SingleActions) {
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001356 // Make sure we can lipo this kind of output. If not (and it is an actual
1357 // output) then we disallow, since we can't create an output file with the
1358 // right name without overwriting it. We could remove this oddity by just
1359 // changing the output names to include the arch, which would also fix
Daniel Dunbarf479c122009-03-12 18:40:18 +00001360 // -save-temps. Compatibility wins for now.
1361
Daniel Dunbare2ca3bd2009-03-13 17:46:02 +00001362 if (Archs.size() > 1 && !types::canLipoType(Act->getType()))
Daniel Dunbarf479c122009-03-12 18:40:18 +00001363 Diag(clang::diag::err_drv_invalid_output_with_multiple_archs)
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001364 << types::getTypeName(Act->getType());
Daniel Dunbarf479c122009-03-12 18:40:18 +00001365
1366 ActionList Inputs;
Justin Lebar41094612016-01-11 23:07:27 +00001367 for (unsigned i = 0, e = Archs.size(); i != e; ++i)
1368 Inputs.push_back(C.MakeAction<BindArchAction>(Act, Archs[i]));
Daniel Dunbarf479c122009-03-12 18:40:18 +00001369
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001370 // Lipo if necessary, we do it this way because we need to set the arch flag
1371 // so that -Xarch_ gets overwritten.
Daniel Dunbarf479c122009-03-12 18:40:18 +00001372 if (Inputs.size() == 1 || Act->getType() == types::TY_Nothing)
1373 Actions.append(Inputs.begin(), Inputs.end());
1374 else
Justin Lebar41094612016-01-11 23:07:27 +00001375 Actions.push_back(C.MakeAction<LipoJobAction>(Inputs, Act->getType()));
Daniel Dunbar6beaf512010-06-04 18:28:41 +00001376
Eric Christopher65c05fa2012-02-06 19:43:51 +00001377 // Handle debug info queries.
1378 Arg *A = Args.getLastArg(options::OPT_g_Group);
David Blaikie6f9f4eb2012-04-15 21:22:10 +00001379 if (A && !A->getOption().matches(options::OPT_g0) &&
1380 !A->getOption().matches(options::OPT_gstabs) &&
1381 ContainsCompileOrAssembleAction(Actions.back())) {
Chad Rosier62135492012-07-09 17:31:28 +00001382
David Blaikie6f9f4eb2012-04-15 21:22:10 +00001383 // Add a 'dsymutil' step if necessary, when debug info is enabled and we
1384 // have a compile input. We need to run 'dsymutil' ourselves in such cases
Eric Christopher776c26f2013-01-28 17:39:03 +00001385 // because the debug info will refer to a temporary object file which
David Blaikie6f9f4eb2012-04-15 21:22:10 +00001386 // will be removed at the end of the compilation process.
1387 if (Act->getType() == types::TY_Image) {
1388 ActionList Inputs;
1389 Inputs.push_back(Actions.back());
1390 Actions.pop_back();
Justin Lebar41094612016-01-11 23:07:27 +00001391 Actions.push_back(
1392 C.MakeAction<DsymutilJobAction>(Inputs, types::TY_dSYM));
Daniel Dunbar6beaf512010-06-04 18:28:41 +00001393 }
David Blaikie6f9f4eb2012-04-15 21:22:10 +00001394
Ben Langmuir9b9a8d32014-02-06 18:53:25 +00001395 // Verify the debug info output.
Alp Tokere9d2bfc2014-01-17 02:06:23 +00001396 if (Args.hasArg(options::OPT_verify_debug_info)) {
Justin Lebar41094612016-01-11 23:07:27 +00001397 Action* LastAction = Actions.back();
David Blaikie6f9f4eb2012-04-15 21:22:10 +00001398 Actions.pop_back();
Justin Lebar41094612016-01-11 23:07:27 +00001399 Actions.push_back(C.MakeAction<VerifyDebugInfoJobAction>(
1400 LastAction, types::TY_Nothing));
David Blaikie6f9f4eb2012-04-15 21:22:10 +00001401 }
1402 }
Daniel Dunbarf479c122009-03-12 18:40:18 +00001403 }
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00001404}
1405
Hans Wennborg6ee64d52013-08-06 00:20:31 +00001406/// \brief Check that the file referenced by Value exists. If it doesn't,
1407/// issue a diagnostic and return false.
Alp Toker8c8a8752013-12-03 06:53:35 +00001408static bool DiagnoseInputExistence(const Driver &D, const DerivedArgList &Args,
Hans Wennborg12f4f8b2016-04-15 01:12:32 +00001409 StringRef Value, types::ID Ty) {
Hans Wennborg6ee64d52013-08-06 00:20:31 +00001410 if (!D.getCheckInputsExist())
1411 return true;
1412
1413 // stdin always exists.
1414 if (Value == "-")
1415 return true;
1416
1417 SmallString<64> Path(Value);
1418 if (Arg *WorkDir = Args.getLastArg(options::OPT_working_directory)) {
Yaron Keren92e1b622015-03-18 10:17:07 +00001419 if (!llvm::sys::path::is_absolute(Path)) {
Hans Wennborg6ee64d52013-08-06 00:20:31 +00001420 SmallString<64> Directory(WorkDir->getValue());
1421 llvm::sys::path::append(Directory, Value);
1422 Path.assign(Directory);
1423 }
1424 }
1425
1426 if (llvm::sys::fs::exists(Twine(Path)))
1427 return true;
1428
Hans Wennborg12f4f8b2016-04-15 01:12:32 +00001429 if (D.IsCLMode()) {
1430 if (!llvm::sys::path::is_absolute(Twine(Path)) &&
1431 llvm::sys::Process::FindInEnvPath("LIB", Value))
1432 return true;
1433
1434 if (Args.hasArg(options::OPT__SLASH_link) && Ty == types::TY_Object) {
1435 // Arguments to the /link flag might cause the linker to search for object
1436 // and library files in paths we don't know about. Don't error in such
1437 // cases.
1438 return true;
1439 }
1440 }
Hans Wennborg23d26a32014-06-18 17:21:50 +00001441
Yaron Keren92e1b622015-03-18 10:17:07 +00001442 D.Diag(clang::diag::err_drv_no_such_file) << Path;
Hans Wennborg6ee64d52013-08-06 00:20:31 +00001443 return false;
1444}
1445
Chad Rosierecdede82011-08-12 22:08:57 +00001446// Construct a the list of inputs and their types.
Hans Wennborg55362852014-05-02 22:55:30 +00001447void Driver::BuildInputs(const ToolChain &TC, DerivedArgList &Args,
Chad Rosierecdede82011-08-12 22:08:57 +00001448 InputList &Inputs) const {
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001449 // Track the current user specified (-x) input. We also explicitly track the
1450 // argument used to set the type; we only want to claim the type when we
1451 // actually use it, so we warn about unused -x arguments.
Daniel Dunbarc5a5ac52009-03-13 17:57:10 +00001452 types::ID InputType = types::TY_Nothing;
Craig Topper92fc2df2014-05-17 16:56:41 +00001453 Arg *InputTypeArg = nullptr;
Daniel Dunbarc5a5ac52009-03-13 17:57:10 +00001454
Hans Wennborg0d0b19c2013-08-12 18:34:17 +00001455 // The last /TC or /TP option sets the input type to C or C++ globally.
Ehsan Akhgaric249abb2014-09-12 21:44:24 +00001456 if (Arg *TCTP = Args.getLastArgNoClaim(options::OPT__SLASH_TC,
1457 options::OPT__SLASH_TP)) {
Hans Wennborg6ee64d52013-08-06 00:20:31 +00001458 InputTypeArg = TCTP;
Hans Wennborg0d0b19c2013-08-12 18:34:17 +00001459 InputType = TCTP->getOption().matches(options::OPT__SLASH_TC)
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001460 ? types::TY_C
1461 : types::TY_CXX;
Hans Wennborg6ee64d52013-08-06 00:20:31 +00001462
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001463 arg_iterator it =
1464 Args.filtered_begin(options::OPT__SLASH_TC, options::OPT__SLASH_TP);
Hans Wennborg0d0b19c2013-08-12 18:34:17 +00001465 const arg_iterator ie = Args.filtered_end();
1466 Arg *Previous = *it++;
1467 bool ShowNote = false;
1468 while (it != ie) {
Hans Wennborgd9ad0682013-09-11 16:38:41 +00001469 Diag(clang::diag::warn_drv_overriding_flag_option)
1470 << Previous->getSpelling() << (*it)->getSpelling();
Hans Wennborg0d0b19c2013-08-12 18:34:17 +00001471 Previous = *it++;
1472 ShowNote = true;
Hans Wennborg6ee64d52013-08-06 00:20:31 +00001473 }
Hans Wennborg0d0b19c2013-08-12 18:34:17 +00001474 if (ShowNote)
1475 Diag(clang::diag::note_drv_t_option_is_global);
Hans Wennborg6ee64d52013-08-06 00:20:31 +00001476
1477 // No driver mode exposes -x and /TC or /TP; we don't support mixing them.
1478 assert(!Args.hasArg(options::OPT_x) && "-x and /TC or /TP is not allowed");
1479 }
1480
Saleem Abdulrasool688b6bc2014-12-29 19:01:36 +00001481 for (Arg *A : Args) {
Michael J. Spencerad3ccc32012-08-20 21:41:17 +00001482 if (A->getOption().getKind() == Option::InputClass) {
Richard Smithbd55daf2012-11-01 04:30:05 +00001483 const char *Value = A->getValue();
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00001484 types::ID Ty = types::TY_INVALID;
1485
1486 // Infer the input type if necessary.
Daniel Dunbarc5a5ac52009-03-13 17:57:10 +00001487 if (InputType == types::TY_Nothing) {
1488 // If there was an explicit arg for this, claim it.
1489 if (InputTypeArg)
1490 InputTypeArg->claim();
1491
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00001492 // stdin must be handled specially.
1493 if (memcmp(Value, "-", 2) == 0) {
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001494 // If running with -E, treat as a C input (this changes the builtin
1495 // macros, for example). This may be overridden by -ObjC below.
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00001496 //
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001497 // Otherwise emit an error but still use a valid type to avoid
1498 // spurious errors (e.g., no inputs).
Hans Wennborg70850d82013-07-18 20:29:38 +00001499 if (!Args.hasArgNoClaim(options::OPT_E) && !CCCIsCPP())
Hans Wennborgcfdd8b52014-01-29 01:04:40 +00001500 Diag(IsCLMode() ? clang::diag::err_drv_unknown_stdin_type_clang_cl
1501 : clang::diag::err_drv_unknown_stdin_type);
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00001502 Ty = types::TY_C;
1503 } else {
Joerg Sonnenbergerbdbdf702011-03-16 22:45:02 +00001504 // Otherwise lookup by extension.
1505 // Fallback is C if invoked as C preprocessor or Object otherwise.
1506 // We use a host hook here because Darwin at least has its own
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001507 // idea of what .s is.
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00001508 if (const char *Ext = strrchr(Value, '.'))
Daniel Dunbarcc7df6c2010-08-02 05:43:56 +00001509 Ty = TC.LookupTypeForExtension(Ext + 1);
Daniel Dunbarea9f0322009-03-20 23:39:23 +00001510
Joerg Sonnenbergerbdbdf702011-03-16 22:45:02 +00001511 if (Ty == types::TY_INVALID) {
Hans Wennborg70850d82013-07-18 20:29:38 +00001512 if (CCCIsCPP())
Joerg Sonnenbergerbdbdf702011-03-16 22:45:02 +00001513 Ty = types::TY_C;
1514 else
1515 Ty = types::TY_Object;
1516 }
Daniel Dunbar0ac94452010-02-17 20:32:58 +00001517
1518 // If the driver is invoked as C++ compiler (like clang++ or c++) it
1519 // should autodetect some input files as C++ for g++ compatibility.
Hans Wennborg70850d82013-07-18 20:29:38 +00001520 if (CCCIsCXX()) {
Daniel Dunbar0ac94452010-02-17 20:32:58 +00001521 types::ID OldTy = Ty;
1522 Ty = types::lookupCXXTypeForCType(Ty);
1523
1524 if (Ty != OldTy)
1525 Diag(clang::diag::warn_drv_treating_input_as_cxx)
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001526 << getTypeName(OldTy) << getTypeName(Ty);
Daniel Dunbar0ac94452010-02-17 20:32:58 +00001527 }
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00001528 }
1529
Daniel Dunbar82b22102009-05-18 21:47:54 +00001530 // -ObjC and -ObjC++ override the default language, but only for "source
1531 // files". We just treat everything that isn't a linker input as a
1532 // source file.
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001533 //
Daniel Dunbar82b22102009-05-18 21:47:54 +00001534 // FIXME: Clean this up if we move the phase sequence into the type.
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00001535 if (Ty != types::TY_Object) {
1536 if (Args.hasArg(options::OPT_ObjC))
1537 Ty = types::TY_ObjC;
1538 else if (Args.hasArg(options::OPT_ObjCXX))
1539 Ty = types::TY_ObjCXX;
1540 }
1541 } else {
1542 assert(InputTypeArg && "InputType set w/o InputTypeArg");
Ehsan Akhgari7e954ea2014-09-12 18:15:10 +00001543 if (!InputTypeArg->getOption().matches(options::OPT_x)) {
1544 // If emulating cl.exe, make sure that /TC and /TP don't affect input
1545 // object files.
1546 const char *Ext = strrchr(Value, '.');
1547 if (Ext && TC.LookupTypeForExtension(Ext + 1) == types::TY_Object)
1548 Ty = types::TY_Object;
1549 }
1550 if (Ty == types::TY_INVALID) {
1551 Ty = InputType;
1552 InputTypeArg->claim();
1553 }
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00001554 }
1555
Hans Wennborg12f4f8b2016-04-15 01:12:32 +00001556 if (DiagnoseInputExistence(*this, Args, Value, Ty))
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00001557 Inputs.push_back(std::make_pair(Ty, A));
1558
Hans Wennborg6ee64d52013-08-06 00:20:31 +00001559 } else if (A->getOption().matches(options::OPT__SLASH_Tc)) {
1560 StringRef Value = A->getValue();
Hans Wennborg12f4f8b2016-04-15 01:12:32 +00001561 if (DiagnoseInputExistence(*this, Args, Value, types::TY_C)) {
David Blaikie0aaa7622017-01-13 17:34:15 +00001562 Arg *InputArg = MakeInputArg(Args, *Opts, A->getValue());
Hans Wennborg6ee64d52013-08-06 00:20:31 +00001563 Inputs.push_back(std::make_pair(types::TY_C, InputArg));
1564 }
1565 A->claim();
1566 } else if (A->getOption().matches(options::OPT__SLASH_Tp)) {
1567 StringRef Value = A->getValue();
Hans Wennborg12f4f8b2016-04-15 01:12:32 +00001568 if (DiagnoseInputExistence(*this, Args, Value, types::TY_CXX)) {
David Blaikie0aaa7622017-01-13 17:34:15 +00001569 Arg *InputArg = MakeInputArg(Args, *Opts, A->getValue());
Hans Wennborg6ee64d52013-08-06 00:20:31 +00001570 Inputs.push_back(std::make_pair(types::TY_CXX, InputArg));
1571 }
1572 A->claim();
Michael J. Spencer66e2b202012-10-19 22:37:06 +00001573 } else if (A->getOption().hasFlag(options::LinkerInput)) {
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001574 // Just treat as object type, we could make a special type for this if
1575 // necessary.
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00001576 Inputs.push_back(std::make_pair(types::TY_Object, A));
1577
Daniel Dunbar0bfb21e2009-11-19 03:26:40 +00001578 } else if (A->getOption().matches(options::OPT_x)) {
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001579 InputTypeArg = A;
Richard Smithbd55daf2012-11-01 04:30:05 +00001580 InputType = types::lookupTypeForTypeSpecifier(A->getValue());
Chad Rosier706c2352012-04-07 00:01:31 +00001581 A->claim();
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00001582
1583 // Follow gcc behavior and treat as linker input for invalid -x
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001584 // options. Its not clear why we shouldn't just revert to unknown; but
Michael J. Spencer1a4fe8c2010-12-17 21:22:33 +00001585 // this isn't very important, we might as well be bug compatible.
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00001586 if (!InputType) {
Richard Smithbd55daf2012-11-01 04:30:05 +00001587 Diag(clang::diag::err_drv_unknown_language) << A->getValue();
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00001588 InputType = types::TY_Object;
1589 }
1590 }
1591 }
Hans Wennborg70850d82013-07-18 20:29:38 +00001592 if (CCCIsCPP() && Inputs.empty()) {
Joerg Sonnenbergerb86f5f42011-03-06 23:31:01 +00001593 // If called as standalone preprocessor, stdin is processed
1594 // if no other input is present.
David Blaikie0aaa7622017-01-13 17:34:15 +00001595 Arg *A = MakeInputArg(Args, *Opts, "-");
Joerg Sonnenbergerb86f5f42011-03-06 23:31:01 +00001596 Inputs.push_back(std::make_pair(types::TY_C, A));
1597 }
Chad Rosierecdede82011-08-12 22:08:57 +00001598}
1599
Samuel Antao64e965e2016-09-30 15:34:19 +00001600namespace {
1601/// Provides a convenient interface for different programming models to generate
1602/// the required device actions.
1603class OffloadingActionBuilder final {
1604 /// Flag used to trace errors in the builder.
1605 bool IsValid = false;
1606
1607 /// The compilation that is using this builder.
1608 Compilation &C;
1609
Samuel Antao64e965e2016-09-30 15:34:19 +00001610 /// Map between an input argument and the offload kinds used to process it.
1611 std::map<const Arg *, unsigned> InputArgToOffloadKindMap;
1612
1613 /// Builder interface. It doesn't build anything or keep any state.
1614 class DeviceActionBuilder {
1615 public:
1616 typedef llvm::SmallVector<phases::ID, phases::MaxNumberOfPhases> PhasesTy;
1617
1618 enum ActionBuilderReturnCode {
1619 // The builder acted successfully on the current action.
1620 ABRT_Success,
1621 // The builder didn't have to act on the current action.
1622 ABRT_Inactive,
1623 // The builder was successful and requested the host action to not be
1624 // generated.
1625 ABRT_Ignore_Host,
1626 };
1627
1628 protected:
1629 /// Compilation associated with this builder.
1630 Compilation &C;
1631
1632 /// Tool chains associated with this builder. The same programming
1633 /// model may have associated one or more tool chains.
1634 SmallVector<const ToolChain *, 2> ToolChains;
1635
1636 /// The derived arguments associated with this builder.
1637 DerivedArgList &Args;
1638
1639 /// The inputs associated with this builder.
1640 const Driver::InputList &Inputs;
1641
1642 /// The associated offload kind.
1643 Action::OffloadKind AssociatedOffloadKind = Action::OFK_None;
1644
1645 public:
1646 DeviceActionBuilder(Compilation &C, DerivedArgList &Args,
1647 const Driver::InputList &Inputs,
1648 Action::OffloadKind AssociatedOffloadKind)
1649 : C(C), Args(Args), Inputs(Inputs),
1650 AssociatedOffloadKind(AssociatedOffloadKind) {}
1651 virtual ~DeviceActionBuilder() {}
1652
1653 /// Fill up the array \a DA with all the device dependences that should be
1654 /// added to the provided host action \a HostAction. By default it is
1655 /// inactive.
1656 virtual ActionBuilderReturnCode
Samuel Antao28c4f182016-10-27 17:08:03 +00001657 getDeviceDependences(OffloadAction::DeviceDependences &DA,
1658 phases::ID CurPhase, phases::ID FinalPhase,
1659 PhasesTy &Phases) {
Samuel Antao64e965e2016-09-30 15:34:19 +00001660 return ABRT_Inactive;
1661 }
1662
1663 /// Update the state to include the provided host action \a HostAction as a
1664 /// dependency of the current device action. By default it is inactive.
1665 virtual ActionBuilderReturnCode addDeviceDepences(Action *HostAction) {
1666 return ABRT_Inactive;
1667 }
1668
1669 /// Append top level actions generated by the builder. Return true if errors
1670 /// were found.
1671 virtual void appendTopLevelActions(ActionList &AL) {}
1672
1673 /// Append linker actions generated by the builder. Return true if errors
1674 /// were found.
1675 virtual void appendLinkDependences(OffloadAction::DeviceDependences &DA) {}
1676
1677 /// Initialize the builder. Return true if any initialization errors are
1678 /// found.
1679 virtual bool initialize() { return false; }
1680
Samuel Antao69d6f312016-10-27 17:50:43 +00001681 /// Return true if the builder can use bundling/unbundling.
1682 virtual bool canUseBundlerUnbundler() const { return false; }
1683
Samuel Antao64e965e2016-09-30 15:34:19 +00001684 /// Return true if this builder is valid. We have a valid builder if we have
1685 /// associated device tool chains.
1686 bool isValid() { return !ToolChains.empty(); }
1687
1688 /// Return the associated offload kind.
1689 Action::OffloadKind getAssociatedOffloadKind() {
1690 return AssociatedOffloadKind;
1691 }
1692 };
1693
1694 /// \brief CUDA action builder. It injects device code in the host backend
1695 /// action.
1696 class CudaActionBuilder final : public DeviceActionBuilder {
1697 /// Flags to signal if the user requested host-only or device-only
1698 /// compilation.
1699 bool CompileHostOnly = false;
1700 bool CompileDeviceOnly = false;
1701
1702 /// List of GPU architectures to use in this compilation.
1703 SmallVector<CudaArch, 4> GpuArchList;
1704
1705 /// The CUDA actions for the current input.
1706 ActionList CudaDeviceActions;
1707
1708 /// The CUDA fat binary if it was generated for the current input.
1709 Action *CudaFatBinary = nullptr;
1710
1711 /// Flag that is set to true if this builder acted on the current input.
1712 bool IsActive = false;
1713
1714 public:
1715 CudaActionBuilder(Compilation &C, DerivedArgList &Args,
1716 const Driver::InputList &Inputs)
1717 : DeviceActionBuilder(C, Args, Inputs, Action::OFK_Cuda) {}
1718
1719 ActionBuilderReturnCode
Samuel Antao28c4f182016-10-27 17:08:03 +00001720 getDeviceDependences(OffloadAction::DeviceDependences &DA,
1721 phases::ID CurPhase, phases::ID FinalPhase,
1722 PhasesTy &Phases) override {
Samuel Antao64e965e2016-09-30 15:34:19 +00001723 if (!IsActive)
1724 return ABRT_Inactive;
1725
1726 // If we don't have more CUDA actions, we don't have any dependences to
1727 // create for the host.
1728 if (CudaDeviceActions.empty())
1729 return ABRT_Success;
1730
1731 assert(CudaDeviceActions.size() == GpuArchList.size() &&
1732 "Expecting one action per GPU architecture.");
1733 assert(!CompileHostOnly &&
1734 "Not expecting CUDA actions in host-only compilation.");
1735
1736 // If we are generating code for the device or we are in a backend phase,
1737 // we attempt to generate the fat binary. We compile each arch to ptx and
1738 // assemble to cubin, then feed the cubin *and* the ptx into a device
1739 // "link" action, which uses fatbinary to combine these cubins into one
1740 // fatbin. The fatbin is then an input to the host action if not in
1741 // device-only mode.
1742 if (CompileDeviceOnly || CurPhase == phases::Backend) {
1743 ActionList DeviceActions;
1744 for (unsigned I = 0, E = GpuArchList.size(); I != E; ++I) {
1745 // Produce the device action from the current phase up to the assemble
1746 // phase.
1747 for (auto Ph : Phases) {
1748 // Skip the phases that were already dealt with.
1749 if (Ph < CurPhase)
1750 continue;
1751 // We have to be consistent with the host final phase.
1752 if (Ph > FinalPhase)
1753 break;
1754
1755 CudaDeviceActions[I] = C.getDriver().ConstructPhaseAction(
1756 C, Args, Ph, CudaDeviceActions[I]);
1757
1758 if (Ph == phases::Assemble)
1759 break;
1760 }
1761
1762 // If we didn't reach the assemble phase, we can't generate the fat
1763 // binary. We don't need to generate the fat binary if we are not in
1764 // device-only mode.
1765 if (!isa<AssembleJobAction>(CudaDeviceActions[I]) ||
1766 CompileDeviceOnly)
1767 continue;
1768
1769 Action *AssembleAction = CudaDeviceActions[I];
1770 assert(AssembleAction->getType() == types::TY_Object);
1771 assert(AssembleAction->getInputs().size() == 1);
1772
1773 Action *BackendAction = AssembleAction->getInputs()[0];
1774 assert(BackendAction->getType() == types::TY_PP_Asm);
1775
1776 for (auto &A : {AssembleAction, BackendAction}) {
1777 OffloadAction::DeviceDependences DDep;
1778 DDep.add(*A, *ToolChains.front(), CudaArchToString(GpuArchList[I]),
1779 Action::OFK_Cuda);
1780 DeviceActions.push_back(
1781 C.MakeAction<OffloadAction>(DDep, A->getType()));
1782 }
1783 }
1784
1785 // We generate the fat binary if we have device input actions.
1786 if (!DeviceActions.empty()) {
1787 CudaFatBinary =
1788 C.MakeAction<LinkJobAction>(DeviceActions, types::TY_CUDA_FATBIN);
1789
1790 if (!CompileDeviceOnly) {
1791 DA.add(*CudaFatBinary, *ToolChains.front(), /*BoundArch=*/nullptr,
1792 Action::OFK_Cuda);
1793 // Clear the fat binary, it is already a dependence to an host
1794 // action.
1795 CudaFatBinary = nullptr;
1796 }
1797
1798 // Remove the CUDA actions as they are already connected to an host
1799 // action or fat binary.
1800 CudaDeviceActions.clear();
1801 }
1802
1803 // We avoid creating host action in device-only mode.
1804 return CompileDeviceOnly ? ABRT_Ignore_Host : ABRT_Success;
Samuel Antao5b1a89a2016-10-27 00:53:34 +00001805 } else if (CurPhase > phases::Backend) {
1806 // If we are past the backend phase and still have a device action, we
1807 // don't have to do anything as this action is already a device
1808 // top-level action.
1809 return ABRT_Success;
Samuel Antao64e965e2016-09-30 15:34:19 +00001810 }
1811
1812 assert(CurPhase < phases::Backend && "Generating single CUDA "
1813 "instructions should only occur "
1814 "before the backend phase!");
1815
1816 // By default, we produce an action for each device arch.
1817 for (Action *&A : CudaDeviceActions)
1818 A = C.getDriver().ConstructPhaseAction(C, Args, CurPhase, A);
1819
1820 return ABRT_Success;
1821 }
1822
1823 ActionBuilderReturnCode addDeviceDepences(Action *HostAction) override {
1824 // While generating code for CUDA, we only depend on the host input action
1825 // to trigger the creation of all the CUDA device actions.
1826
1827 // If we are dealing with an input action, replicate it for each GPU
1828 // architecture. If we are in host-only mode we return 'success' so that
1829 // the host uses the CUDA offload kind.
1830 if (auto *IA = dyn_cast<InputAction>(HostAction)) {
1831 assert(!GpuArchList.empty() &&
1832 "We should have at least one GPU architecture.");
1833
1834 // If the host input is not CUDA, we don't need to bother about this
1835 // input.
1836 if (IA->getType() != types::TY_CUDA) {
1837 // The builder will ignore this input.
1838 IsActive = false;
1839 return ABRT_Inactive;
1840 }
1841
1842 // Set the flag to true, so that the builder acts on the current input.
1843 IsActive = true;
1844
1845 if (CompileHostOnly)
1846 return ABRT_Success;
1847
1848 // Replicate inputs for each GPU architecture.
1849 for (unsigned I = 0, E = GpuArchList.size(); I != E; ++I)
1850 CudaDeviceActions.push_back(C.MakeAction<InputAction>(
1851 IA->getInputArg(), types::TY_CUDA_DEVICE));
1852
1853 return ABRT_Success;
1854 }
1855
1856 return IsActive ? ABRT_Success : ABRT_Inactive;
1857 }
1858
1859 void appendTopLevelActions(ActionList &AL) override {
1860 // Utility to append actions to the top level list.
1861 auto AddTopLevel = [&](Action *A, CudaArch BoundArch) {
1862 OffloadAction::DeviceDependences Dep;
1863 Dep.add(*A, *ToolChains.front(), CudaArchToString(BoundArch),
1864 Action::OFK_Cuda);
1865 AL.push_back(C.MakeAction<OffloadAction>(Dep, A->getType()));
1866 };
1867
1868 // If we have a fat binary, add it to the list.
1869 if (CudaFatBinary) {
1870 AddTopLevel(CudaFatBinary, CudaArch::UNKNOWN);
1871 CudaDeviceActions.clear();
1872 CudaFatBinary = nullptr;
1873 return;
1874 }
1875
1876 if (CudaDeviceActions.empty())
1877 return;
1878
1879 // If we have CUDA actions at this point, that's because we have a have
1880 // partial compilation, so we should have an action for each GPU
1881 // architecture.
1882 assert(CudaDeviceActions.size() == GpuArchList.size() &&
1883 "Expecting one action per GPU architecture.");
1884 assert(ToolChains.size() == 1 &&
1885 "Expecting to have a sing CUDA toolchain.");
1886 for (unsigned I = 0, E = GpuArchList.size(); I != E; ++I)
1887 AddTopLevel(CudaDeviceActions[I], GpuArchList[I]);
1888
1889 CudaDeviceActions.clear();
1890 }
1891
1892 bool initialize() override {
1893 // We don't need to support CUDA.
1894 if (!C.hasOffloadToolChain<Action::OFK_Cuda>())
1895 return false;
1896
1897 const ToolChain *HostTC = C.getSingleOffloadToolChain<Action::OFK_Host>();
1898 assert(HostTC && "No toolchain for host compilation.");
1899 if (HostTC->getTriple().isNVPTX()) {
1900 // We do not support targeting NVPTX for host compilation. Throw
1901 // an error and abort pipeline construction early so we don't trip
1902 // asserts that assume device-side compilation.
1903 C.getDriver().Diag(diag::err_drv_cuda_nvptx_host);
1904 return true;
1905 }
1906
1907 ToolChains.push_back(C.getSingleOffloadToolChain<Action::OFK_Cuda>());
1908
1909 Arg *PartialCompilationArg = Args.getLastArg(
1910 options::OPT_cuda_host_only, options::OPT_cuda_device_only,
1911 options::OPT_cuda_compile_host_device);
1912 CompileHostOnly = PartialCompilationArg &&
1913 PartialCompilationArg->getOption().matches(
1914 options::OPT_cuda_host_only);
1915 CompileDeviceOnly = PartialCompilationArg &&
1916 PartialCompilationArg->getOption().matches(
1917 options::OPT_cuda_device_only);
1918
1919 // Collect all cuda_gpu_arch parameters, removing duplicates.
Artem Belevicha424e882016-12-09 22:59:17 +00001920 std::set<CudaArch> GpuArchs;
Samuel Antao64e965e2016-09-30 15:34:19 +00001921 bool Error = false;
1922 for (Arg *A : Args) {
Artem Belevicha424e882016-12-09 22:59:17 +00001923 if (!(A->getOption().matches(options::OPT_cuda_gpu_arch_EQ) ||
1924 A->getOption().matches(options::OPT_no_cuda_gpu_arch_EQ)))
Samuel Antao64e965e2016-09-30 15:34:19 +00001925 continue;
1926 A->claim();
1927
Artem Belevicha424e882016-12-09 22:59:17 +00001928 const StringRef ArchStr = A->getValue();
1929 if (A->getOption().matches(options::OPT_no_cuda_gpu_arch_EQ) &&
1930 ArchStr == "all") {
1931 GpuArchs.clear();
1932 continue;
1933 }
Samuel Antao64e965e2016-09-30 15:34:19 +00001934 CudaArch Arch = StringToCudaArch(ArchStr);
1935 if (Arch == CudaArch::UNKNOWN) {
1936 C.getDriver().Diag(clang::diag::err_drv_cuda_bad_gpu_arch) << ArchStr;
1937 Error = true;
Artem Belevicha424e882016-12-09 22:59:17 +00001938 } else if (A->getOption().matches(options::OPT_cuda_gpu_arch_EQ))
1939 GpuArchs.insert(Arch);
1940 else if (A->getOption().matches(options::OPT_no_cuda_gpu_arch_EQ))
1941 GpuArchs.erase(Arch);
1942 else
1943 llvm_unreachable("Unexpected option.");
Samuel Antao64e965e2016-09-30 15:34:19 +00001944 }
1945
Artem Belevicha424e882016-12-09 22:59:17 +00001946 // Collect list of GPUs remaining in the set.
1947 for (CudaArch Arch : GpuArchs)
1948 GpuArchList.push_back(Arch);
1949
1950 // Default to sm_20 which is the lowest common denominator for
1951 // supported GPUs. sm_20 code should work correctly, if
1952 // suboptimally, on all newer GPUs.
Samuel Antao64e965e2016-09-30 15:34:19 +00001953 if (GpuArchList.empty())
1954 GpuArchList.push_back(CudaArch::SM_20);
1955
1956 return Error;
1957 }
1958 };
1959
Samuel Antao28c4f182016-10-27 17:08:03 +00001960 /// OpenMP action builder. The host bitcode is passed to the device frontend
1961 /// and all the device linked images are passed to the host link phase.
1962 class OpenMPActionBuilder final : public DeviceActionBuilder {
1963 /// The OpenMP actions for the current input.
1964 ActionList OpenMPDeviceActions;
1965
1966 /// The linker inputs obtained for each toolchain.
1967 SmallVector<ActionList, 8> DeviceLinkerInputs;
1968
1969 public:
1970 OpenMPActionBuilder(Compilation &C, DerivedArgList &Args,
1971 const Driver::InputList &Inputs)
1972 : DeviceActionBuilder(C, Args, Inputs, Action::OFK_OpenMP) {}
1973
1974 ActionBuilderReturnCode
1975 getDeviceDependences(OffloadAction::DeviceDependences &DA,
1976 phases::ID CurPhase, phases::ID FinalPhase,
1977 PhasesTy &Phases) override {
1978
1979 // We should always have an action for each input.
1980 assert(OpenMPDeviceActions.size() == ToolChains.size() &&
1981 "Number of OpenMP actions and toolchains do not match.");
1982
1983 // The host only depends on device action in the linking phase, when all
1984 // the device images have to be embedded in the host image.
1985 if (CurPhase == phases::Link) {
1986 assert(ToolChains.size() == DeviceLinkerInputs.size() &&
1987 "Toolchains and linker inputs sizes do not match.");
1988 auto LI = DeviceLinkerInputs.begin();
1989 for (auto *A : OpenMPDeviceActions) {
1990 LI->push_back(A);
1991 ++LI;
1992 }
1993
1994 // We passed the device action as a host dependence, so we don't need to
1995 // do anything else with them.
1996 OpenMPDeviceActions.clear();
1997 return ABRT_Success;
1998 }
1999
2000 // By default, we produce an action for each device arch.
2001 for (Action *&A : OpenMPDeviceActions)
2002 A = C.getDriver().ConstructPhaseAction(C, Args, CurPhase, A);
2003
2004 return ABRT_Success;
2005 }
2006
2007 ActionBuilderReturnCode addDeviceDepences(Action *HostAction) override {
2008
2009 // If this is an input action replicate it for each OpenMP toolchain.
2010 if (auto *IA = dyn_cast<InputAction>(HostAction)) {
2011 OpenMPDeviceActions.clear();
2012 for (unsigned I = 0; I < ToolChains.size(); ++I)
2013 OpenMPDeviceActions.push_back(
2014 C.MakeAction<InputAction>(IA->getInputArg(), IA->getType()));
2015 return ABRT_Success;
2016 }
2017
Samuel Antaofab4f372016-10-27 18:00:51 +00002018 // If this is an unbundling action use it as is for each OpenMP toolchain.
2019 if (auto *UA = dyn_cast<OffloadUnbundlingJobAction>(HostAction)) {
2020 OpenMPDeviceActions.clear();
2021 for (unsigned I = 0; I < ToolChains.size(); ++I) {
2022 OpenMPDeviceActions.push_back(UA);
2023 UA->registerDependentActionInfo(
2024 ToolChains[I], /*BoundArch=*/StringRef(), Action::OFK_OpenMP);
2025 }
2026 return ABRT_Success;
2027 }
2028
Samuel Antao28c4f182016-10-27 17:08:03 +00002029 // When generating code for OpenMP we use the host compile phase result as
2030 // a dependence to the device compile phase so that it can learn what
2031 // declarations should be emitted. However, this is not the only use for
2032 // the host action, so we prevent it from being collapsed.
2033 if (isa<CompileJobAction>(HostAction)) {
2034 HostAction->setCannotBeCollapsedWithNextDependentAction();
2035 assert(ToolChains.size() == OpenMPDeviceActions.size() &&
2036 "Toolchains and device action sizes do not match.");
2037 OffloadAction::HostDependence HDep(
2038 *HostAction, *C.getSingleOffloadToolChain<Action::OFK_Host>(),
2039 /*BoundArch=*/nullptr, Action::OFK_OpenMP);
2040 auto TC = ToolChains.begin();
2041 for (Action *&A : OpenMPDeviceActions) {
2042 assert(isa<CompileJobAction>(A));
2043 OffloadAction::DeviceDependences DDep;
2044 DDep.add(*A, **TC, /*BoundArch=*/nullptr, Action::OFK_OpenMP);
2045 A = C.MakeAction<OffloadAction>(HDep, DDep);
2046 ++TC;
2047 }
2048 }
2049 return ABRT_Success;
2050 }
2051
Samuel Antao69d6f312016-10-27 17:50:43 +00002052 void appendTopLevelActions(ActionList &AL) override {
2053 if (OpenMPDeviceActions.empty())
2054 return;
2055
2056 // We should always have an action for each input.
2057 assert(OpenMPDeviceActions.size() == ToolChains.size() &&
2058 "Number of OpenMP actions and toolchains do not match.");
2059
2060 // Append all device actions followed by the proper offload action.
2061 auto TI = ToolChains.begin();
2062 for (auto *A : OpenMPDeviceActions) {
2063 OffloadAction::DeviceDependences Dep;
2064 Dep.add(*A, **TI, /*BoundArch=*/nullptr, Action::OFK_OpenMP);
2065 AL.push_back(C.MakeAction<OffloadAction>(Dep, A->getType()));
2066 ++TI;
2067 }
2068 // We no longer need the action stored in this builder.
2069 OpenMPDeviceActions.clear();
2070 }
2071
Samuel Antao28c4f182016-10-27 17:08:03 +00002072 void appendLinkDependences(OffloadAction::DeviceDependences &DA) override {
2073 assert(ToolChains.size() == DeviceLinkerInputs.size() &&
2074 "Toolchains and linker inputs sizes do not match.");
2075
2076 // Append a new link action for each device.
2077 auto TC = ToolChains.begin();
2078 for (auto &LI : DeviceLinkerInputs) {
2079 auto *DeviceLinkAction =
2080 C.MakeAction<LinkJobAction>(LI, types::TY_Image);
2081 DA.add(*DeviceLinkAction, **TC, /*BoundArch=*/nullptr,
2082 Action::OFK_OpenMP);
2083 ++TC;
2084 }
2085 }
2086
2087 bool initialize() override {
2088 // Get the OpenMP toolchains. If we don't get any, the action builder will
2089 // know there is nothing to do related to OpenMP offloading.
2090 auto OpenMPTCRange = C.getOffloadToolChains<Action::OFK_OpenMP>();
2091 for (auto TI = OpenMPTCRange.first, TE = OpenMPTCRange.second; TI != TE;
2092 ++TI)
2093 ToolChains.push_back(TI->second);
2094
2095 DeviceLinkerInputs.resize(ToolChains.size());
2096 return false;
2097 }
Samuel Antao69d6f312016-10-27 17:50:43 +00002098
2099 bool canUseBundlerUnbundler() const override {
2100 // OpenMP should use bundled files whenever possible.
2101 return true;
2102 }
Samuel Antao28c4f182016-10-27 17:08:03 +00002103 };
2104
2105 ///
2106 /// TODO: Add the implementation for other specialized builders here.
2107 ///
Samuel Antao64e965e2016-09-30 15:34:19 +00002108
2109 /// Specialized builders being used by this offloading action builder.
2110 SmallVector<DeviceActionBuilder *, 4> SpecializedBuilders;
2111
Samuel Antao69d6f312016-10-27 17:50:43 +00002112 /// Flag set to true if all valid builders allow file bundling/unbundling.
2113 bool CanUseBundler;
2114
Samuel Antao64e965e2016-09-30 15:34:19 +00002115public:
2116 OffloadingActionBuilder(Compilation &C, DerivedArgList &Args,
2117 const Driver::InputList &Inputs)
Samuel Antao10e905c2016-10-27 01:08:58 +00002118 : C(C) {
Samuel Antao64e965e2016-09-30 15:34:19 +00002119 // Create a specialized builder for each device toolchain.
2120
2121 IsValid = true;
2122
2123 // Create a specialized builder for CUDA.
2124 SpecializedBuilders.push_back(new CudaActionBuilder(C, Args, Inputs));
2125
Samuel Antao28c4f182016-10-27 17:08:03 +00002126 // Create a specialized builder for OpenMP.
2127 SpecializedBuilders.push_back(new OpenMPActionBuilder(C, Args, Inputs));
2128
Samuel Antao64e965e2016-09-30 15:34:19 +00002129 //
2130 // TODO: Build other specialized builders here.
2131 //
2132
Samuel Antao69d6f312016-10-27 17:50:43 +00002133 // Initialize all the builders, keeping track of errors. If all valid
2134 // builders agree that we can use bundling, set the flag to true.
2135 unsigned ValidBuilders = 0u;
2136 unsigned ValidBuildersSupportingBundling = 0u;
2137 for (auto *SB : SpecializedBuilders) {
Samuel Antao64e965e2016-09-30 15:34:19 +00002138 IsValid = IsValid && !SB->initialize();
Samuel Antao69d6f312016-10-27 17:50:43 +00002139
2140 // Update the counters if the builder is valid.
2141 if (SB->isValid()) {
2142 ++ValidBuilders;
2143 if (SB->canUseBundlerUnbundler())
2144 ++ValidBuildersSupportingBundling;
2145 }
2146 }
2147 CanUseBundler =
2148 ValidBuilders && ValidBuilders == ValidBuildersSupportingBundling;
Artem Belevichf981e30b2016-08-02 22:37:47 +00002149 }
Justin Lebardc3c5042016-04-19 02:27:07 +00002150
Samuel Antao64e965e2016-09-30 15:34:19 +00002151 ~OffloadingActionBuilder() {
2152 for (auto *SB : SpecializedBuilders)
2153 delete SB;
Samuel Antaod06239d2016-07-15 23:13:27 +00002154 }
Artem Belevich0ff05cd2015-07-13 23:27:56 +00002155
Samuel Antao64e965e2016-09-30 15:34:19 +00002156 /// Generate an action that adds device dependences (if any) to a host action.
2157 /// If no device dependence actions exist, just return the host action \a
2158 /// HostAction. If an error is found or if no builder requires the host action
2159 /// to be generated, return nullptr.
2160 Action *
2161 addDeviceDependencesToHostAction(Action *HostAction, const Arg *InputArg,
2162 phases::ID CurPhase, phases::ID FinalPhase,
2163 DeviceActionBuilder::PhasesTy &Phases) {
2164 if (!IsValid)
2165 return nullptr;
Justin Lebar7bf77982016-01-11 23:27:13 +00002166
Samuel Antao64e965e2016-09-30 15:34:19 +00002167 if (SpecializedBuilders.empty())
2168 return HostAction;
2169
2170 assert(HostAction && "Invalid host action!");
2171
2172 OffloadAction::DeviceDependences DDeps;
2173 // Check if all the programming models agree we should not emit the host
2174 // action. Also, keep track of the offloading kinds employed.
2175 auto &OffloadKind = InputArgToOffloadKindMap[InputArg];
2176 unsigned InactiveBuilders = 0u;
2177 unsigned IgnoringBuilders = 0u;
2178 for (auto *SB : SpecializedBuilders) {
2179 if (!SB->isValid()) {
2180 ++InactiveBuilders;
2181 continue;
2182 }
2183
Samuel Antao28c4f182016-10-27 17:08:03 +00002184 auto RetCode =
2185 SB->getDeviceDependences(DDeps, CurPhase, FinalPhase, Phases);
Samuel Antao64e965e2016-09-30 15:34:19 +00002186
2187 // If the builder explicitly says the host action should be ignored,
2188 // we need to increment the variable that tracks the builders that request
2189 // the host object to be ignored.
2190 if (RetCode == DeviceActionBuilder::ABRT_Ignore_Host)
2191 ++IgnoringBuilders;
2192
2193 // Unless the builder was inactive for this action, we have to record the
2194 // offload kind because the host will have to use it.
2195 if (RetCode != DeviceActionBuilder::ABRT_Inactive)
2196 OffloadKind |= SB->getAssociatedOffloadKind();
2197 }
2198
2199 // If all builders agree that the host object should be ignored, just return
2200 // nullptr.
2201 if (IgnoringBuilders &&
2202 SpecializedBuilders.size() == (InactiveBuilders + IgnoringBuilders))
2203 return nullptr;
2204
2205 if (DDeps.getActions().empty())
2206 return HostAction;
2207
2208 // We have dependences we need to bundle together. We use an offload action
2209 // for that.
2210 OffloadAction::HostDependence HDep(
2211 *HostAction, *C.getSingleOffloadToolChain<Action::OFK_Host>(),
2212 /*BoundArch=*/nullptr, DDeps);
2213 return C.MakeAction<OffloadAction>(HDep, DDeps);
Artem Belevich0ff05cd2015-07-13 23:27:56 +00002214 }
2215
Samuel Antao64e965e2016-09-30 15:34:19 +00002216 /// Generate an action that adds a host dependence to a device action. The
2217 /// results will be kept in this action builder. Return true if an error was
2218 /// found.
Samuel Antaofab4f372016-10-27 18:00:51 +00002219 bool addHostDependenceToDeviceActions(Action *&HostAction,
Samuel Antao64e965e2016-09-30 15:34:19 +00002220 const Arg *InputArg) {
2221 if (!IsValid)
2222 return true;
Artem Belevich0ff05cd2015-07-13 23:27:56 +00002223
Samuel Antaofab4f372016-10-27 18:00:51 +00002224 // If we are supporting bundling/unbundling and the current action is an
2225 // input action of non-source file, we replace the host action by the
2226 // unbundling action. The bundler tool has the logic to detect if an input
2227 // is a bundle or not and if the input is not a bundle it assumes it is a
2228 // host file. Therefore it is safe to create an unbundling action even if
2229 // the input is not a bundle.
2230 if (CanUseBundler && isa<InputAction>(HostAction) &&
2231 InputArg->getOption().getKind() == llvm::opt::Option::InputClass &&
2232 !types::isSrcFile(HostAction->getType())) {
2233 auto UnbundlingHostAction =
2234 C.MakeAction<OffloadUnbundlingJobAction>(HostAction);
2235 UnbundlingHostAction->registerDependentActionInfo(
2236 C.getSingleOffloadToolChain<Action::OFK_Host>(),
2237 /*BoundArch=*/StringRef(), Action::OFK_Host);
2238 HostAction = UnbundlingHostAction;
2239 }
2240
Samuel Antao64e965e2016-09-30 15:34:19 +00002241 assert(HostAction && "Invalid host action!");
Artem Belevich0ff05cd2015-07-13 23:27:56 +00002242
Samuel Antao64e965e2016-09-30 15:34:19 +00002243 // Register the offload kinds that are used.
2244 auto &OffloadKind = InputArgToOffloadKindMap[InputArg];
2245 for (auto *SB : SpecializedBuilders) {
2246 if (!SB->isValid())
2247 continue;
Artem Belevich0ff05cd2015-07-13 23:27:56 +00002248
Samuel Antao64e965e2016-09-30 15:34:19 +00002249 auto RetCode = SB->addDeviceDepences(HostAction);
Artem Belevich0ff05cd2015-07-13 23:27:56 +00002250
Samuel Antao64e965e2016-09-30 15:34:19 +00002251 // Host dependences for device actions are not compatible with that same
2252 // action being ignored.
2253 assert(RetCode != DeviceActionBuilder::ABRT_Ignore_Host &&
2254 "Host dependence not expected to be ignored.!");
Samuel Antaod06239d2016-07-15 23:13:27 +00002255
Samuel Antao64e965e2016-09-30 15:34:19 +00002256 // Unless the builder was inactive for this action, we have to record the
2257 // offload kind because the host will have to use it.
2258 if (RetCode != DeviceActionBuilder::ABRT_Inactive)
2259 OffloadKind |= SB->getAssociatedOffloadKind();
2260 }
Artem Belevich0ff05cd2015-07-13 23:27:56 +00002261
Samuel Antao64e965e2016-09-30 15:34:19 +00002262 return false;
2263 }
2264
Samuel Antao69d6f312016-10-27 17:50:43 +00002265 /// Add the offloading top level actions to the provided action list. This
2266 /// function can replace the host action by a bundling action if the
2267 /// programming models allow it.
Samuel Antao64e965e2016-09-30 15:34:19 +00002268 bool appendTopLevelActions(ActionList &AL, Action *HostAction,
2269 const Arg *InputArg) {
Samuel Antao69d6f312016-10-27 17:50:43 +00002270 // Get the device actions to be appended.
2271 ActionList OffloadAL;
Samuel Antao64e965e2016-09-30 15:34:19 +00002272 for (auto *SB : SpecializedBuilders) {
2273 if (!SB->isValid())
2274 continue;
Samuel Antao69d6f312016-10-27 17:50:43 +00002275 SB->appendTopLevelActions(OffloadAL);
Samuel Antao64e965e2016-09-30 15:34:19 +00002276 }
2277
Samuel Antao69d6f312016-10-27 17:50:43 +00002278 // If we can use the bundler, replace the host action by the bundling one in
2279 // the resulting list. Otherwise, just append the device actions.
2280 if (CanUseBundler && !OffloadAL.empty()) {
2281 // Add the host action to the list in order to create the bundling action.
2282 OffloadAL.push_back(HostAction);
2283
2284 // We expect that the host action was just appended to the action list
2285 // before this method was called.
2286 assert(HostAction == AL.back() && "Host action not in the list??");
2287 HostAction = C.MakeAction<OffloadBundlingJobAction>(OffloadAL);
2288 AL.back() = HostAction;
2289 } else
2290 AL.append(OffloadAL.begin(), OffloadAL.end());
2291
Samuel Antao64e965e2016-09-30 15:34:19 +00002292 // Propagate to the current host action (if any) the offload information
2293 // associated with the current input.
2294 if (HostAction)
2295 HostAction->propagateHostOffloadInfo(InputArgToOffloadKindMap[InputArg],
2296 /*BoundArch=*/nullptr);
Samuel Antao64e965e2016-09-30 15:34:19 +00002297 return false;
Artem Belevich0ff05cd2015-07-13 23:27:56 +00002298 }
Artem Belevich5bde4e02015-07-20 20:02:54 +00002299
Samuel Antao64e965e2016-09-30 15:34:19 +00002300 /// Processes the host linker action. This currently consists of replacing it
2301 /// with an offload action if there are device link objects and propagate to
2302 /// the host action all the offload kinds used in the current compilation. The
2303 /// resulting action is returned.
2304 Action *processHostLinkAction(Action *HostAction) {
2305 // Add all the dependences from the device linking actions.
2306 OffloadAction::DeviceDependences DDeps;
2307 for (auto *SB : SpecializedBuilders) {
2308 if (!SB->isValid())
2309 continue;
Justin Lebar21e5d4f2016-01-14 21:41:27 +00002310
Samuel Antao64e965e2016-09-30 15:34:19 +00002311 SB->appendLinkDependences(DDeps);
Justin Lebar21e5d4f2016-01-14 21:41:27 +00002312 }
Samuel Antaod06239d2016-07-15 23:13:27 +00002313
Samuel Antao64e965e2016-09-30 15:34:19 +00002314 // Calculate all the offload kinds used in the current compilation.
2315 unsigned ActiveOffloadKinds = 0u;
2316 for (auto &I : InputArgToOffloadKindMap)
2317 ActiveOffloadKinds |= I.second;
2318
2319 // If we don't have device dependencies, we don't have to create an offload
2320 // action.
2321 if (DDeps.getActions().empty()) {
2322 // Propagate all the active kinds to host action. Given that it is a link
2323 // action it is assumed to depend on all actions generated so far.
2324 HostAction->propagateHostOffloadInfo(ActiveOffloadKinds,
2325 /*BoundArch=*/nullptr);
2326 return HostAction;
2327 }
2328
2329 // Create the offload action with all dependences. When an offload action
2330 // is created the kinds are propagated to the host action, so we don't have
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00002331 // to do that explicitly here.
Samuel Antao64e965e2016-09-30 15:34:19 +00002332 OffloadAction::HostDependence HDep(
2333 *HostAction, *C.getSingleOffloadToolChain<Action::OFK_Host>(),
2334 /*BoundArch*/ nullptr, ActiveOffloadKinds);
2335 return C.MakeAction<OffloadAction>(HDep, DDeps);
2336 }
2337};
2338} // anonymous namespace.
Artem Belevich0ff05cd2015-07-13 23:27:56 +00002339
Justin Lebar0f3474c2016-02-11 02:00:50 +00002340void Driver::BuildActions(Compilation &C, DerivedArgList &Args,
2341 const InputList &Inputs, ActionList &Actions) const {
Chad Rosierecdede82011-08-12 22:08:57 +00002342 llvm::PrettyStackTraceString CrashInfo("Building compilation actions");
Joerg Sonnenbergerb86f5f42011-03-06 23:31:01 +00002343
Daniel Dunbar34c41872009-03-13 00:17:48 +00002344 if (!SuppressMissingInputWarning && Inputs.empty()) {
Daniel Dunbarbfeec742009-03-12 23:55:14 +00002345 Diag(clang::diag::err_drv_no_input_files);
2346 return;
2347 }
2348
Chad Rosier7742b5d2011-07-27 23:36:45 +00002349 Arg *FinalPhaseArg;
2350 phases::ID FinalPhase = getFinalPhase(Args, &FinalPhaseArg);
Daniel Dunbarbfeec742009-03-12 23:55:14 +00002351
Rafael Espindolae8025642013-08-25 14:27:09 +00002352 if (FinalPhase == phases::Link && Args.hasArg(options::OPT_emit_llvm)) {
2353 Diag(clang::diag::err_drv_emit_llvm_link);
2354 }
2355
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00002356 // Reject -Z* at the top level, these options should never have been exposed
2357 // by gcc.
Daniel Dunbardd765242009-03-26 16:12:09 +00002358 if (Arg *A = Args.getLastArg(options::OPT_Z_Joined))
Daniel Dunbar0e759942009-03-20 06:14:23 +00002359 Diag(clang::diag::err_drv_use_of_Z_option) << A->getAsString(Args);
Daniel Dunbarbfeec742009-03-12 23:55:14 +00002360
Hans Wennborg13b7fe72013-08-12 23:26:25 +00002361 // Diagnose misuse of /Fo.
2362 if (Arg *A = Args.getLastArg(options::OPT__SLASH_Fo)) {
Hans Wennborg13b7fe72013-08-12 23:26:25 +00002363 StringRef V = A->getValue();
Hans Wennborg61647532014-11-17 19:16:36 +00002364 if (Inputs.size() > 1 && !V.empty() &&
2365 !llvm::sys::path::is_separator(V.back())) {
Hans Wennborg13b7fe72013-08-12 23:26:25 +00002366 // Check whether /Fo tries to name an output file for multiple inputs.
Hans Wennborg9c1659b2013-10-18 22:49:04 +00002367 Diag(clang::diag::err_drv_out_file_argument_with_multiple_sources)
Douglas Katzmana67e50c2015-06-26 15:47:46 +00002368 << A->getSpelling() << V;
Hans Wennborg13b7fe72013-08-12 23:26:25 +00002369 Args.eraseArg(options::OPT__SLASH_Fo);
2370 }
2371 }
2372
Hans Wennborg9c1659b2013-10-18 22:49:04 +00002373 // Diagnose misuse of /Fa.
2374 if (Arg *A = Args.getLastArg(options::OPT__SLASH_Fa)) {
2375 StringRef V = A->getValue();
Hans Wennborg61647532014-11-17 19:16:36 +00002376 if (Inputs.size() > 1 && !V.empty() &&
2377 !llvm::sys::path::is_separator(V.back())) {
Hans Wennborg9c1659b2013-10-18 22:49:04 +00002378 // Check whether /Fa tries to name an asm file for multiple inputs.
2379 Diag(clang::diag::err_drv_out_file_argument_with_multiple_sources)
Douglas Katzmana67e50c2015-06-26 15:47:46 +00002380 << A->getSpelling() << V;
Hans Wennborg9c1659b2013-10-18 22:49:04 +00002381 Args.eraseArg(options::OPT__SLASH_Fa);
2382 }
2383 }
2384
Ehsan Akhgari81f36b72014-09-11 18:16:21 +00002385 // Diagnose misuse of /o.
2386 if (Arg *A = Args.getLastArg(options::OPT__SLASH_o)) {
2387 if (A->getValue()[0] == '\0') {
2388 // It has to have a value.
2389 Diag(clang::diag::err_drv_missing_argument) << A->getSpelling() << 1;
2390 Args.eraseArg(options::OPT__SLASH_o);
2391 }
2392 }
2393
Nico Weber2ca4be92016-03-01 23:16:44 +00002394 // Diagnose unsupported forms of /Yc /Yu. Ignore /Yc/Yu for now if:
2395 // * no filename after it
2396 // * both /Yc and /Yu passed but with different filenames
2397 // * corresponding file not also passed as /FI
2398 Arg *YcArg = Args.getLastArg(options::OPT__SLASH_Yc);
2399 Arg *YuArg = Args.getLastArg(options::OPT__SLASH_Yu);
2400 if (YcArg && YcArg->getValue()[0] == '\0') {
2401 Diag(clang::diag::warn_drv_ycyu_no_arg_clang_cl) << YcArg->getSpelling();
2402 Args.eraseArg(options::OPT__SLASH_Yc);
2403 YcArg = nullptr;
2404 }
2405 if (YuArg && YuArg->getValue()[0] == '\0') {
2406 Diag(clang::diag::warn_drv_ycyu_no_arg_clang_cl) << YuArg->getSpelling();
2407 Args.eraseArg(options::OPT__SLASH_Yu);
2408 YuArg = nullptr;
2409 }
2410 if (YcArg && YuArg && strcmp(YcArg->getValue(), YuArg->getValue()) != 0) {
2411 Diag(clang::diag::warn_drv_ycyu_different_arg_clang_cl);
2412 Args.eraseArg(options::OPT__SLASH_Yc);
2413 Args.eraseArg(options::OPT__SLASH_Yu);
2414 YcArg = YuArg = nullptr;
2415 }
2416 if (YcArg || YuArg) {
2417 StringRef Val = YcArg ? YcArg->getValue() : YuArg->getValue();
2418 bool FoundMatchingInclude = false;
2419 for (const Arg *Inc : Args.filtered(options::OPT_include)) {
2420 // FIXME: Do case-insensitive matching and consider / and \ as equal.
2421 if (Inc->getValue() == Val)
2422 FoundMatchingInclude = true;
2423 }
2424 if (!FoundMatchingInclude) {
2425 Diag(clang::diag::warn_drv_ycyu_no_fi_arg_clang_cl)
2426 << (YcArg ? YcArg : YuArg)->getSpelling();
2427 Args.eraseArg(options::OPT__SLASH_Yc);
2428 Args.eraseArg(options::OPT__SLASH_Yu);
2429 YcArg = YuArg = nullptr;
2430 }
2431 }
2432 if (YcArg && Inputs.size() > 1) {
2433 Diag(clang::diag::warn_drv_yc_multiple_inputs_clang_cl);
2434 Args.eraseArg(options::OPT__SLASH_Yc);
2435 YcArg = nullptr;
2436 }
2437 if (Args.hasArg(options::OPT__SLASH_Y_)) {
2438 // /Y- disables all pch handling. Rather than check for it everywhere,
2439 // just remove clang-cl pch-related flags here.
2440 Args.eraseArg(options::OPT__SLASH_Fp);
2441 Args.eraseArg(options::OPT__SLASH_Yc);
2442 Args.eraseArg(options::OPT__SLASH_Yu);
2443 YcArg = YuArg = nullptr;
2444 }
Nico Weber2ca4be92016-03-01 23:16:44 +00002445
Samuel Antao64e965e2016-09-30 15:34:19 +00002446 // Builder to be used to build offloading actions.
2447 OffloadingActionBuilder OffloadBuilder(C, Args, Inputs);
Samuel Antaod06239d2016-07-15 23:13:27 +00002448
Daniel Dunbar65229332009-03-13 11:38:42 +00002449 // Construct the actions to perform.
2450 ActionList LinkerInputs;
Alp Toker965f8822013-11-27 05:22:15 +00002451
Matthew Curtis7ab8b2b2013-03-07 12:32:26 +00002452 llvm::SmallVector<phases::ID, phases::MaxNumberOfPhases> PL;
Artem Belevich5bde4e02015-07-20 20:02:54 +00002453 for (auto &I : Inputs) {
2454 types::ID InputType = I.first;
2455 const Arg *InputArg = I.second;
Daniel Dunbar65229332009-03-13 11:38:42 +00002456
Matthew Curtis7ab8b2b2013-03-07 12:32:26 +00002457 PL.clear();
2458 types::getCompilationPhases(InputType, PL);
Daniel Dunbar65229332009-03-13 11:38:42 +00002459
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00002460 // If the first step comes after the final phase we are doing as part of
2461 // this compilation, warn the user about it.
Matthew Curtis7ab8b2b2013-03-07 12:32:26 +00002462 phases::ID InitialPhase = PL[0];
Daniel Dunbar65229332009-03-13 11:38:42 +00002463 if (InitialPhase > FinalPhase) {
Daniel Dunbaradc5c7c2009-03-19 07:57:08 +00002464 // Claim here to avoid the more general unused warning.
2465 InputArg->claim();
Daniel Dunbar07806ca2009-09-17 04:13:26 +00002466
Daniel Dunbar2db3e732011-04-20 15:44:48 +00002467 // Suppress all unused style warnings with -Qunused-arguments
2468 if (Args.hasArg(options::OPT_Qunused_arguments))
2469 continue;
2470
Richard Smith403f76e2012-08-06 04:09:06 +00002471 // Special case when final phase determined by binary name, rather than
2472 // by a command-line argument with a corresponding Arg.
Hans Wennborg70850d82013-07-18 20:29:38 +00002473 if (CCCIsCPP())
Richard Smith403f76e2012-08-06 04:09:06 +00002474 Diag(clang::diag::warn_drv_input_file_unused_by_cpp)
Douglas Katzmana67e50c2015-06-26 15:47:46 +00002475 << InputArg->getAsString(Args) << getPhaseName(InitialPhase);
Daniel Dunbar07806ca2009-09-17 04:13:26 +00002476 // Special case '-E' warning on a previously preprocessed file to make
2477 // more sense.
Richard Smith403f76e2012-08-06 04:09:06 +00002478 else if (InitialPhase == phases::Compile &&
2479 FinalPhase == phases::Preprocess &&
2480 getPreprocessedType(InputType) == types::TY_INVALID)
Daniel Dunbar07806ca2009-09-17 04:13:26 +00002481 Diag(clang::diag::warn_drv_preprocessed_input_file_unused)
Douglas Katzmana67e50c2015-06-26 15:47:46 +00002482 << InputArg->getAsString(Args) << !!FinalPhaseArg
2483 << (FinalPhaseArg ? FinalPhaseArg->getOption().getName() : "");
Daniel Dunbar07806ca2009-09-17 04:13:26 +00002484 else
2485 Diag(clang::diag::warn_drv_input_file_unused)
Douglas Katzmana67e50c2015-06-26 15:47:46 +00002486 << InputArg->getAsString(Args) << getPhaseName(InitialPhase)
2487 << !!FinalPhaseArg
2488 << (FinalPhaseArg ? FinalPhaseArg->getOption().getName() : "");
Daniel Dunbar65229332009-03-13 11:38:42 +00002489 continue;
2490 }
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00002491
Nico Weberad2d8f32016-04-21 19:59:10 +00002492 if (YcArg) {
2493 // Add a separate precompile phase for the compile phase.
2494 if (FinalPhase >= phases::Compile) {
Richard Smith8cd452d2016-08-30 18:55:16 +00002495 const types::ID HeaderType = lookupHeaderTypeForSourceType(InputType);
Nico Weberad2d8f32016-04-21 19:59:10 +00002496 llvm::SmallVector<phases::ID, phases::MaxNumberOfPhases> PCHPL;
Richard Smith8cd452d2016-08-30 18:55:16 +00002497 types::getCompilationPhases(HeaderType, PCHPL);
David Blaikie0aaa7622017-01-13 17:34:15 +00002498 Arg *PchInputArg = MakeInputArg(Args, *Opts, YcArg->getValue());
Nico Weberad2d8f32016-04-21 19:59:10 +00002499
2500 // Build the pipeline for the pch file.
Richard Smith8cd452d2016-08-30 18:55:16 +00002501 Action *ClangClPch =
2502 C.MakeAction<InputAction>(*PchInputArg, HeaderType);
Nico Weberad2d8f32016-04-21 19:59:10 +00002503 for (phases::ID Phase : PCHPL)
2504 ClangClPch = ConstructPhaseAction(C, Args, Phase, ClangClPch);
2505 assert(ClangClPch);
2506 Actions.push_back(ClangClPch);
2507 // The driver currently exits after the first failed command. This
2508 // relies on that behavior, to make sure if the pch generation fails,
2509 // the main compilation won't run.
2510 }
2511 }
2512
Daniel Dunbar65229332009-03-13 11:38:42 +00002513 // Build the pipeline for this file.
Justin Lebar41094612016-01-11 23:07:27 +00002514 Action *Current = C.MakeAction<InputAction>(*InputArg, InputType);
Samuel Antao64e965e2016-09-30 15:34:19 +00002515
2516 // Use the current host action in any of the offloading actions, if
2517 // required.
2518 if (OffloadBuilder.addHostDependenceToDeviceActions(Current, InputArg))
2519 break;
2520
Douglas Katzmana67e50c2015-06-26 15:47:46 +00002521 for (SmallVectorImpl<phases::ID>::iterator i = PL.begin(), e = PL.end();
2522 i != e; ++i) {
Matthew Curtis7ab8b2b2013-03-07 12:32:26 +00002523 phases::ID Phase = *i;
Daniel Dunbar65229332009-03-13 11:38:42 +00002524
2525 // We are done if this step is past what the user requested.
2526 if (Phase > FinalPhase)
2527 break;
2528
Samuel Antao64e965e2016-09-30 15:34:19 +00002529 // Add any offload action the host action depends on.
2530 Current = OffloadBuilder.addDeviceDependencesToHostAction(
2531 Current, InputArg, Phase, FinalPhase, PL);
2532 if (!Current)
2533 break;
2534
Daniel Dunbar65229332009-03-13 11:38:42 +00002535 // Queue linker inputs.
2536 if (Phase == phases::Link) {
Matthew Curtis7ab8b2b2013-03-07 12:32:26 +00002537 assert((i + 1) == e && "linking must be final compilation step.");
Justin Lebar41094612016-01-11 23:07:27 +00002538 LinkerInputs.push_back(Current);
2539 Current = nullptr;
Daniel Dunbar65229332009-03-13 11:38:42 +00002540 break;
2541 }
2542
Samuel Antao64e965e2016-09-30 15:34:19 +00002543 // Otherwise construct the appropriate action.
2544 auto *NewCurrent = ConstructPhaseAction(C, Args, Phase, Current);
2545
2546 // We didn't create a new action, so we will just move to the next phase.
2547 if (NewCurrent == Current)
Daniel Dunbar13864952009-03-24 20:17:30 +00002548 continue;
2549
Samuel Antao64e965e2016-09-30 15:34:19 +00002550 Current = NewCurrent;
Artem Belevich0ff05cd2015-07-13 23:27:56 +00002551
Samuel Antao64e965e2016-09-30 15:34:19 +00002552 // Use the current host action in any of the offloading actions, if
2553 // required.
2554 if (OffloadBuilder.addHostDependenceToDeviceActions(Current, InputArg))
2555 break;
Artem Belevich0ff05cd2015-07-13 23:27:56 +00002556
Daniel Dunbar65229332009-03-13 11:38:42 +00002557 if (Current->getType() == types::TY_Nothing)
2558 break;
2559 }
2560
Samuel Antao64e965e2016-09-30 15:34:19 +00002561 // If we ended with something, add to the output list.
2562 if (Current)
Justin Lebar41094612016-01-11 23:07:27 +00002563 Actions.push_back(Current);
Samuel Antao64e965e2016-09-30 15:34:19 +00002564
2565 // Add any top level actions generated for offloading.
2566 OffloadBuilder.appendTopLevelActions(Actions, Current, InputArg);
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00002567 }
Daniel Dunbar65229332009-03-13 11:38:42 +00002568
Samuel Antao64e965e2016-09-30 15:34:19 +00002569 // Add a link action if necessary.
Samuel Antaod06239d2016-07-15 23:13:27 +00002570 if (!LinkerInputs.empty()) {
Samuel Antao64e965e2016-09-30 15:34:19 +00002571 Action *LA = C.MakeAction<LinkJobAction>(LinkerInputs, types::TY_Image);
2572 LA = OffloadBuilder.processHostLinkAction(LA);
2573 Actions.push_back(LA);
Samuel Antaod06239d2016-07-15 23:13:27 +00002574 }
Daniel Dunbarc7a67b72009-12-22 23:19:32 +00002575
2576 // If we are linking, claim any options which are obviously only used for
2577 // compilation.
Hans Wennborga8ef14f2013-09-17 00:03:41 +00002578 if (FinalPhase == phases::Link && PL.size() == 1) {
Daniel Dunbarc7a67b72009-12-22 23:19:32 +00002579 Args.ClaimAllArgs(options::OPT_CompileOnly_Group);
Hans Wennborga8ef14f2013-09-17 00:03:41 +00002580 Args.ClaimAllArgs(options::OPT_cl_compile_Group);
2581 }
2582
2583 // Claim ignored clang-cl options.
2584 Args.ClaimAllArgs(options::OPT_cl_ignored_Group);
Artem Belevichbaae0932015-07-28 21:01:30 +00002585
Justin Lebardc3c5042016-04-19 02:27:07 +00002586 // Claim --cuda-host-only and --cuda-compile-host-device, which may be passed
2587 // to non-CUDA compilations and should not trigger warnings there.
Artem Belevichbaae0932015-07-28 21:01:30 +00002588 Args.ClaimAllArgs(options::OPT_cuda_host_only);
Justin Lebardc3c5042016-04-19 02:27:07 +00002589 Args.ClaimAllArgs(options::OPT_cuda_compile_host_device);
Daniel Dunbar65229332009-03-13 11:38:42 +00002590}
2591
Justin Lebar0f3474c2016-02-11 02:00:50 +00002592Action *Driver::ConstructPhaseAction(Compilation &C, const ArgList &Args,
2593 phases::ID Phase, Action *Input) const {
Daniel Dunbar2608c542009-03-18 01:38:48 +00002594 llvm::PrettyStackTraceString CrashInfo("Constructing phase actions");
Samuel Antao64e965e2016-09-30 15:34:19 +00002595
2596 // Some types skip the assembler phase (e.g., llvm-bc), but we can't
2597 // encode this in the steps because the intermediate type depends on
2598 // arguments. Just special case here.
2599 if (Phase == phases::Assemble && Input->getType() != types::TY_PP_Asm)
2600 return Input;
2601
Daniel Dunbar65229332009-03-13 11:38:42 +00002602 // Build the appropriate action.
2603 switch (Phase) {
Douglas Katzmana67e50c2015-06-26 15:47:46 +00002604 case phases::Link:
2605 llvm_unreachable("link action invalid here.");
Daniel Dunbar65229332009-03-13 11:38:42 +00002606 case phases::Preprocess: {
Daniel Dunbard67a3222009-03-30 06:36:42 +00002607 types::ID OutputTy;
2608 // -{M, MM} alter the output type.
Daniel Dunbar86aed7d2010-12-08 21:33:40 +00002609 if (Args.hasArg(options::OPT_M, options::OPT_MM)) {
Daniel Dunbard67a3222009-03-30 06:36:42 +00002610 OutputTy = types::TY_Dependencies;
2611 } else {
David Blaikie5d577a22012-06-29 22:03:56 +00002612 OutputTy = Input->getType();
2613 if (!Args.hasFlag(options::OPT_frewrite_includes,
Justin Bognerce8245b2014-06-24 08:01:01 +00002614 options::OPT_fno_rewrite_includes, false) &&
2615 !CCGenDiagnostics)
David Blaikie5d577a22012-06-29 22:03:56 +00002616 OutputTy = types::getPreprocessedType(OutputTy);
Daniel Dunbard67a3222009-03-30 06:36:42 +00002617 assert(OutputTy != types::TY_INVALID &&
2618 "Cannot preprocess this input type!");
2619 }
Justin Lebar41094612016-01-11 23:07:27 +00002620 return C.MakeAction<PreprocessJobAction>(Input, OutputTy);
Daniel Dunbar65229332009-03-13 11:38:42 +00002621 }
Aaron Ballman1f10cc52012-07-31 01:21:00 +00002622 case phases::Precompile: {
Richard Smithdd4ad3d2016-08-30 19:06:26 +00002623 types::ID OutputTy = getPrecompiledType(Input->getType());
2624 assert(OutputTy != types::TY_INVALID &&
2625 "Cannot precompile this input type!");
Aaron Ballman1f10cc52012-07-31 01:21:00 +00002626 if (Args.hasArg(options::OPT_fsyntax_only)) {
2627 // Syntax checks should not emit a PCH file
2628 OutputTy = types::TY_Nothing;
2629 }
Justin Lebar41094612016-01-11 23:07:27 +00002630 return C.MakeAction<PrecompileJobAction>(Input, OutputTy);
Aaron Ballman1f10cc52012-07-31 01:21:00 +00002631 }
Daniel Dunbar65229332009-03-13 11:38:42 +00002632 case phases::Compile: {
David Blaikie486f4402014-08-29 07:25:23 +00002633 if (Args.hasArg(options::OPT_fsyntax_only))
Justin Lebar41094612016-01-11 23:07:27 +00002634 return C.MakeAction<CompileJobAction>(Input, types::TY_Nothing);
David Blaikie486f4402014-08-29 07:25:23 +00002635 if (Args.hasArg(options::OPT_rewrite_objc))
Justin Lebar41094612016-01-11 23:07:27 +00002636 return C.MakeAction<CompileJobAction>(Input, types::TY_RewrittenObjC);
David Blaikie486f4402014-08-29 07:25:23 +00002637 if (Args.hasArg(options::OPT_rewrite_legacy_objc))
Justin Lebar41094612016-01-11 23:07:27 +00002638 return C.MakeAction<CompileJobAction>(Input,
2639 types::TY_RewrittenLegacyObjC);
David Blaikie486f4402014-08-29 07:25:23 +00002640 if (Args.hasArg(options::OPT__analyze, options::OPT__analyze_auto))
Justin Lebar41094612016-01-11 23:07:27 +00002641 return C.MakeAction<AnalyzeJobAction>(Input, types::TY_Plist);
David Blaikie486f4402014-08-29 07:25:23 +00002642 if (Args.hasArg(options::OPT__migrate))
Justin Lebar41094612016-01-11 23:07:27 +00002643 return C.MakeAction<MigrateJobAction>(Input, types::TY_Remap);
David Blaikie486f4402014-08-29 07:25:23 +00002644 if (Args.hasArg(options::OPT_emit_ast))
Justin Lebar41094612016-01-11 23:07:27 +00002645 return C.MakeAction<CompileJobAction>(Input, types::TY_AST);
David Blaikie486f4402014-08-29 07:25:23 +00002646 if (Args.hasArg(options::OPT_module_file_info))
Justin Lebar41094612016-01-11 23:07:27 +00002647 return C.MakeAction<CompileJobAction>(Input, types::TY_ModuleFile);
David Blaikie486f4402014-08-29 07:25:23 +00002648 if (Args.hasArg(options::OPT_verify_pch))
Justin Lebar41094612016-01-11 23:07:27 +00002649 return C.MakeAction<VerifyPCHJobAction>(Input, types::TY_Nothing);
2650 return C.MakeAction<CompileJobAction>(Input, types::TY_LLVM_BC);
Bob Wilson23a55f12014-12-21 07:00:00 +00002651 }
2652 case phases::Backend: {
Teresa Johnson945bc502015-10-15 20:35:53 +00002653 if (isUsingLTO()) {
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00002654 types::ID Output =
Douglas Katzmana67e50c2015-06-26 15:47:46 +00002655 Args.hasArg(options::OPT_S) ? types::TY_LTO_IR : types::TY_LTO_BC;
Justin Lebar41094612016-01-11 23:07:27 +00002656 return C.MakeAction<BackendJobAction>(Input, Output);
David Blaikie486f4402014-08-29 07:25:23 +00002657 }
2658 if (Args.hasArg(options::OPT_emit_llvm)) {
Shuxin Yang4b3c7ff2013-08-23 21:34:57 +00002659 types::ID Output =
Douglas Katzmana67e50c2015-06-26 15:47:46 +00002660 Args.hasArg(options::OPT_S) ? types::TY_LLVM_IR : types::TY_LLVM_BC;
Justin Lebar41094612016-01-11 23:07:27 +00002661 return C.MakeAction<BackendJobAction>(Input, Output);
Daniel Dunbar65229332009-03-13 11:38:42 +00002662 }
Justin Lebar41094612016-01-11 23:07:27 +00002663 return C.MakeAction<BackendJobAction>(Input, types::TY_PP_Asm);
Daniel Dunbar65229332009-03-13 11:38:42 +00002664 }
2665 case phases::Assemble:
Justin Lebar21e5d4f2016-01-14 21:41:27 +00002666 return C.MakeAction<AssembleJobAction>(std::move(Input), types::TY_Object);
Daniel Dunbar65229332009-03-13 11:38:42 +00002667 }
2668
David Blaikie83d382b2011-09-23 05:06:16 +00002669 llvm_unreachable("invalid phase in ConstructPhaseAction");
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00002670}
2671
Daniel Dunbarf0eddb82009-03-18 02:55:38 +00002672void Driver::BuildJobs(Compilation &C) const {
Daniel Dunbar2608c542009-03-18 01:38:48 +00002673 llvm::PrettyStackTraceString CrashInfo("Building compilation jobs");
Daniel Dunbare75d8342009-03-16 06:56:51 +00002674
2675 Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o);
2676
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00002677 // It is an error to provide a -o option if we are making multiple output
2678 // files.
Daniel Dunbare75d8342009-03-16 06:56:51 +00002679 if (FinalOutput) {
2680 unsigned NumOutputs = 0;
Saleem Abdulrasoolda3f4e52014-12-29 21:02:47 +00002681 for (const Action *A : C.getActions())
2682 if (A->getType() != types::TY_Nothing)
Daniel Dunbare75d8342009-03-16 06:56:51 +00002683 ++NumOutputs;
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00002684
Daniel Dunbare75d8342009-03-16 06:56:51 +00002685 if (NumOutputs > 1) {
2686 Diag(clang::diag::err_drv_output_argument_with_multiple_files);
Craig Topper92fc2df2014-05-17 16:56:41 +00002687 FinalOutput = nullptr;
Daniel Dunbare75d8342009-03-16 06:56:51 +00002688 }
2689 }
2690
Chad Rosier35767232013-04-30 22:01:21 +00002691 // Collect the list of architectures.
2692 llvm::StringSet<> ArchNames;
Saleem Abdulrasool688b6bc2014-12-29 19:01:36 +00002693 if (C.getDefaultToolChain().getTriple().isOSBinFormatMachO())
2694 for (const Arg *A : C.getArgs())
Chad Rosier35767232013-04-30 22:01:21 +00002695 if (A->getOption().matches(options::OPT_arch))
2696 ArchNames.insert(A->getValue());
Chad Rosier35767232013-04-30 22:01:21 +00002697
Justin Lebarb44f6fe2016-01-14 21:41:21 +00002698 // Set of (Action, canonical ToolChain triple) pairs we've built jobs for.
2699 std::map<std::pair<const Action *, std::string>, InputInfo> CachedResults;
Saleem Abdulrasool688b6bc2014-12-29 19:01:36 +00002700 for (Action *A : C.getActions()) {
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00002701 // If we are linking an image for multiple archs then the linker wants
2702 // -arch_multiple and -final_output <final image name>. Unfortunately, this
2703 // doesn't fit in cleanly because we have to pass this information down.
Daniel Dunbare75d8342009-03-16 06:56:51 +00002704 //
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00002705 // FIXME: This is a hack; find a cleaner way to integrate this into the
2706 // process.
Craig Topper92fc2df2014-05-17 16:56:41 +00002707 const char *LinkingOutput = nullptr;
Daniel Dunbardd765242009-03-26 16:12:09 +00002708 if (isa<LipoJobAction>(A)) {
Daniel Dunbare75d8342009-03-16 06:56:51 +00002709 if (FinalOutput)
Richard Smithbd55daf2012-11-01 04:30:05 +00002710 LinkingOutput = FinalOutput->getValue();
Daniel Dunbare75d8342009-03-16 06:56:51 +00002711 else
Hans Wennborga7707222015-01-09 17:38:53 +00002712 LinkingOutput = getDefaultImageName();
Daniel Dunbare75d8342009-03-16 06:56:51 +00002713 }
2714
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00002715 BuildJobsForAction(C, A, &C.getDefaultToolChain(),
Mehdi Aminic50b1a22016-10-07 21:27:26 +00002716 /*BoundArch*/ StringRef(),
Daniel Dunbare75d8342009-03-16 06:56:51 +00002717 /*AtTopLevel*/ true,
Chad Rosier35767232013-04-30 22:01:21 +00002718 /*MultipleArchs*/ ArchNames.size() > 1,
Samuel Antaod06239d2016-07-15 23:13:27 +00002719 /*LinkingOutput*/ LinkingOutput, CachedResults,
Samuel Antao3b7e38b2016-10-27 18:14:55 +00002720 /*TargetDeviceOffloadKind*/ Action::OFK_None);
Daniel Dunbare75d8342009-03-16 06:56:51 +00002721 }
Daniel Dunbar3ce436d2009-03-16 06:42:30 +00002722
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00002723 // If the user passed -Qunused-arguments or there were errors, don't warn
2724 // about any unused arguments.
Argyrios Kyrtzidis31448a42010-11-18 21:47:07 +00002725 if (Diags.hasErrorOccurred() ||
Daniel Dunbara3cfbe32009-04-07 19:04:18 +00002726 C.getArgs().hasArg(options::OPT_Qunused_arguments))
Daniel Dunbard175d972009-03-18 18:03:46 +00002727 return;
2728
Daniel Dunbar58399ae2009-03-29 22:24:54 +00002729 // Claim -### here.
Douglas Katzmana67e50c2015-06-26 15:47:46 +00002730 (void)C.getArgs().hasArg(options::OPT__HASH_HASH_HASH);
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00002731
Nico Weber47bf5052016-04-25 21:15:49 +00002732 // Claim --driver-mode, --rsp-quoting, it was handled earlier.
Douglas Katzmana67e50c2015-06-26 15:47:46 +00002733 (void)C.getArgs().hasArg(options::OPT_driver_mode);
Nico Weber47bf5052016-04-25 21:15:49 +00002734 (void)C.getArgs().hasArg(options::OPT_rsp_quoting);
Hans Wennborg70850d82013-07-18 20:29:38 +00002735
Saleem Abdulrasool688b6bc2014-12-29 19:01:36 +00002736 for (Arg *A : C.getArgs()) {
Daniel Dunbar3ce436d2009-03-16 06:42:30 +00002737 // FIXME: It would be nice to be able to send the argument to the
David Blaikie9c902b52011-09-25 23:23:43 +00002738 // DiagnosticsEngine, so that extra values, position, and so on could be
2739 // printed.
Daniel Dunbar90dd6f42009-04-04 00:52:26 +00002740 if (!A->isClaimed()) {
Michael J. Spencer66e2b202012-10-19 22:37:06 +00002741 if (A->getOption().hasFlag(options::NoArgumentUnused))
Daniel Dunbara3cfbe32009-04-07 19:04:18 +00002742 continue;
2743
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00002744 // Suppress the warning automatically if this is just a flag, and it is an
2745 // instance of an argument we already claimed.
Daniel Dunbar90dd6f42009-04-04 00:52:26 +00002746 const Option &Opt = A->getOption();
Michael J. Spencerad3ccc32012-08-20 21:41:17 +00002747 if (Opt.getKind() == Option::FlagClass) {
Daniel Dunbar90dd6f42009-04-04 00:52:26 +00002748 bool DuplicateClaimed = false;
2749
Sean Silva14facf32015-06-09 01:57:17 +00002750 for (const Arg *AA : C.getArgs().filtered(&Opt)) {
2751 if (AA->isClaimed()) {
Daniel Dunbar90dd6f42009-04-04 00:52:26 +00002752 DuplicateClaimed = true;
2753 break;
2754 }
2755 }
2756
2757 if (DuplicateClaimed)
2758 continue;
2759 }
2760
Ehsan Akhgarid8518332016-01-25 21:14:52 +00002761 // In clang-cl, don't mention unknown arguments here since they have
2762 // already been warned about.
2763 if (!IsCLMode() || !A->getOption().matches(options::OPT_UNKNOWN))
2764 Diag(clang::diag::warn_drv_unused_argument)
2765 << A->getAsString(C.getArgs());
Daniel Dunbar90dd6f42009-04-04 00:52:26 +00002766 }
Daniel Dunbar3ce436d2009-03-16 06:42:30 +00002767 }
Daniel Dunbar95e6b192009-03-13 22:12:33 +00002768}
Daniel Dunbarc4343942010-02-03 03:07:56 +00002769
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00002770namespace {
2771/// Utility class to control the collapse of dependent actions and select the
2772/// tools accordingly.
2773class ToolSelector final {
2774 /// The tool chain this selector refers to.
2775 const ToolChain &TC;
Daniel Dunbarf9ff3502010-05-14 02:03:00 +00002776
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00002777 /// The compilation this selector refers to.
2778 const Compilation &C;
Samuel Antaod06239d2016-07-15 23:13:27 +00002779
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00002780 /// The base action this selector refers to.
2781 const JobAction *BaseAction;
Samuel Antaod06239d2016-07-15 23:13:27 +00002782
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00002783 /// Set to true if the current toolchain refers to host actions.
2784 bool IsHostSelector;
Samuel Antaod06239d2016-07-15 23:13:27 +00002785
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00002786 /// Set to true if save-temps and embed-bitcode functionalities are active.
2787 bool SaveTemps;
2788 bool EmbedBitcode;
2789
2790 /// Get previous dependent action or null if that does not exist. If
2791 /// \a CanBeCollapsed is false, that action must be legal to collapse or
2792 /// null will be returned.
2793 const JobAction *getPrevDependentAction(const ActionList &Inputs,
2794 ActionList &SavedOffloadAction,
2795 bool CanBeCollapsed = true) {
2796 // An option can be collapsed only if it has a single input.
2797 if (Inputs.size() != 1)
Craig Topper92fc2df2014-05-17 16:56:41 +00002798 return nullptr;
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00002799
2800 Action *CurAction = *Inputs.begin();
2801 if (CanBeCollapsed &&
2802 !CurAction->isCollapsingWithNextDependentActionLegal())
2803 return nullptr;
2804
2805 // If the input action is an offload action. Look through it and save any
2806 // offload action that can be dropped in the event of a collapse.
2807 if (auto *OA = dyn_cast<OffloadAction>(CurAction)) {
2808 // If the dependent action is a device action, we will attempt to collapse
2809 // only with other device actions. Otherwise, we would do the same but
2810 // with host actions only.
2811 if (!IsHostSelector) {
2812 if (OA->hasSingleDeviceDependence(/*DoNotConsiderHostActions=*/true)) {
2813 CurAction =
2814 OA->getSingleDeviceDependence(/*DoNotConsiderHostActions=*/true);
2815 if (CanBeCollapsed &&
2816 !CurAction->isCollapsingWithNextDependentActionLegal())
2817 return nullptr;
2818 SavedOffloadAction.push_back(OA);
2819 return dyn_cast<JobAction>(CurAction);
2820 }
2821 } else if (OA->hasHostDependence()) {
2822 CurAction = OA->getHostDependence();
2823 if (CanBeCollapsed &&
2824 !CurAction->isCollapsingWithNextDependentActionLegal())
2825 return nullptr;
2826 SavedOffloadAction.push_back(OA);
2827 return dyn_cast<JobAction>(CurAction);
2828 }
2829 return nullptr;
2830 }
2831
2832 return dyn_cast<JobAction>(CurAction);
2833 }
2834
2835 /// Return true if an assemble action can be collapsed.
2836 bool canCollapseAssembleAction() const {
2837 return TC.useIntegratedAs() && !SaveTemps &&
2838 !C.getArgs().hasArg(options::OPT_via_file_asm) &&
2839 !C.getArgs().hasArg(options::OPT__SLASH_FA) &&
2840 !C.getArgs().hasArg(options::OPT__SLASH_Fa);
2841 }
2842
2843 /// Return true if a preprocessor action can be collapsed.
2844 bool canCollapsePreprocessorAction() const {
2845 return !C.getArgs().hasArg(options::OPT_no_integrated_cpp) &&
2846 !C.getArgs().hasArg(options::OPT_traditional_cpp) && !SaveTemps &&
2847 !C.getArgs().hasArg(options::OPT_rewrite_objc);
2848 }
2849
2850 /// Struct that relates an action with the offload actions that would be
2851 /// collapsed with it.
2852 struct JobActionInfo final {
2853 /// The action this info refers to.
2854 const JobAction *JA = nullptr;
2855 /// The offload actions we need to take care off if this action is
2856 /// collapsed.
2857 ActionList SavedOffloadAction;
2858 };
2859
2860 /// Append collapsed offload actions from the give nnumber of elements in the
2861 /// action info array.
2862 static void AppendCollapsedOffloadAction(ActionList &CollapsedOffloadAction,
2863 ArrayRef<JobActionInfo> &ActionInfo,
2864 unsigned ElementNum) {
2865 assert(ElementNum <= ActionInfo.size() && "Invalid number of elements.");
2866 for (unsigned I = 0; I < ElementNum; ++I)
2867 CollapsedOffloadAction.append(ActionInfo[I].SavedOffloadAction.begin(),
2868 ActionInfo[I].SavedOffloadAction.end());
2869 }
2870
2871 /// Functions that attempt to perform the combining. They detect if that is
2872 /// legal, and if so they update the inputs \a Inputs and the offload action
2873 /// that were collapsed in \a CollapsedOffloadAction. A tool that deals with
2874 /// the combined action is returned. If the combining is not legal or if the
2875 /// tool does not exist, null is returned.
2876 /// Currently three kinds of collapsing are supported:
2877 /// - Assemble + Backend + Compile;
2878 /// - Assemble + Backend ;
2879 /// - Backend + Compile.
2880 const Tool *
2881 combineAssembleBackendCompile(ArrayRef<JobActionInfo> ActionInfo,
2882 const ActionList *&Inputs,
2883 ActionList &CollapsedOffloadAction) {
2884 if (ActionInfo.size() < 3 || !canCollapseAssembleAction())
2885 return nullptr;
2886 auto *AJ = dyn_cast<AssembleJobAction>(ActionInfo[0].JA);
2887 auto *BJ = dyn_cast<BackendJobAction>(ActionInfo[1].JA);
2888 auto *CJ = dyn_cast<CompileJobAction>(ActionInfo[2].JA);
2889 if (!AJ || !BJ || !CJ)
2890 return nullptr;
2891
2892 // Get compiler tool.
2893 const Tool *T = TC.SelectTool(*CJ);
2894 if (!T)
2895 return nullptr;
2896
Steven Wu574b0f22016-03-01 01:07:58 +00002897 // When using -fembed-bitcode, it is required to have the same tool (clang)
2898 // for both CompilerJA and BackendJA. Otherwise, combine two stages.
2899 if (EmbedBitcode) {
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00002900 const Tool *BT = TC.SelectTool(*BJ);
2901 if (BT == T)
2902 return nullptr;
Steven Wu574b0f22016-03-01 01:07:58 +00002903 }
Bob Wilson23a55f12014-12-21 07:00:00 +00002904
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00002905 if (!T->hasIntegratedAssembler())
Bob Wilson23a55f12014-12-21 07:00:00 +00002906 return nullptr;
Samuel Antaod06239d2016-07-15 23:13:27 +00002907
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00002908 Inputs = &CJ->getInputs();
2909 AppendCollapsedOffloadAction(CollapsedOffloadAction, ActionInfo,
2910 /*NumElements=*/3);
2911 return T;
2912 }
2913 const Tool *combineAssembleBackend(ArrayRef<JobActionInfo> ActionInfo,
2914 const ActionList *&Inputs,
2915 ActionList &CollapsedOffloadAction) {
2916 if (ActionInfo.size() < 2 || !canCollapseAssembleAction())
2917 return nullptr;
2918 auto *AJ = dyn_cast<AssembleJobAction>(ActionInfo[0].JA);
2919 auto *BJ = dyn_cast<BackendJobAction>(ActionInfo[1].JA);
2920 if (!AJ || !BJ)
2921 return nullptr;
2922
2923 // Retrieve the compile job, backend action must always be preceded by one.
2924 ActionList CompileJobOffloadActions;
2925 auto *CJ = getPrevDependentAction(BJ->getInputs(), CompileJobOffloadActions,
2926 /*CanBeCollapsed=*/false);
2927 if (!AJ || !BJ || !CJ)
2928 return nullptr;
2929
2930 assert(isa<CompileJobAction>(CJ) &&
2931 "Expecting compile job preceding backend job.");
2932
2933 // Get compiler tool.
2934 const Tool *T = TC.SelectTool(*CJ);
2935 if (!T)
2936 return nullptr;
2937
2938 if (!T->hasIntegratedAssembler())
2939 return nullptr;
2940
2941 Inputs = &BJ->getInputs();
2942 AppendCollapsedOffloadAction(CollapsedOffloadAction, ActionInfo,
2943 /*NumElements=*/2);
2944 return T;
2945 }
2946 const Tool *combineBackendCompile(ArrayRef<JobActionInfo> ActionInfo,
2947 const ActionList *&Inputs,
2948 ActionList &CollapsedOffloadAction) {
2949 if (ActionInfo.size() < 2 || !canCollapsePreprocessorAction())
2950 return nullptr;
2951 auto *BJ = dyn_cast<BackendJobAction>(ActionInfo[0].JA);
2952 auto *CJ = dyn_cast<CompileJobAction>(ActionInfo[1].JA);
2953 if (!BJ || !CJ)
2954 return nullptr;
2955
2956 // Get compiler tool.
2957 const Tool *T = TC.SelectTool(*CJ);
2958 if (!T)
2959 return nullptr;
2960
2961 if (T->canEmitIR() && (SaveTemps || EmbedBitcode))
2962 return nullptr;
2963
2964 Inputs = &CJ->getInputs();
2965 AppendCollapsedOffloadAction(CollapsedOffloadAction, ActionInfo,
2966 /*NumElements=*/2);
2967 return T;
2968 }
2969
2970 /// Updates the inputs if the obtained tool supports combining with
2971 /// preprocessor action, and the current input is indeed a preprocessor
2972 /// action. If combining results in the collapse of offloading actions, those
2973 /// are appended to \a CollapsedOffloadAction.
2974 void combineWithPreprocessor(const Tool *T, const ActionList *&Inputs,
2975 ActionList &CollapsedOffloadAction) {
2976 if (!T || !canCollapsePreprocessorAction() || !T->hasIntegratedCPP())
2977 return;
2978
2979 // Attempt to get a preprocessor action dependence.
2980 ActionList PreprocessJobOffloadActions;
2981 auto *PJ = getPrevDependentAction(*Inputs, PreprocessJobOffloadActions);
2982 if (!PJ || !isa<PreprocessJobAction>(PJ))
2983 return;
2984
2985 // This is legal to combine. Append any offload action we found and set the
2986 // current inputs to preprocessor inputs.
2987 CollapsedOffloadAction.append(PreprocessJobOffloadActions.begin(),
2988 PreprocessJobOffloadActions.end());
2989 Inputs = &PJ->getInputs();
2990 }
2991
2992public:
2993 ToolSelector(const JobAction *BaseAction, const ToolChain &TC,
2994 const Compilation &C, bool SaveTemps, bool EmbedBitcode)
2995 : TC(TC), C(C), BaseAction(BaseAction), SaveTemps(SaveTemps),
2996 EmbedBitcode(EmbedBitcode) {
2997 assert(BaseAction && "Invalid base action.");
2998 IsHostSelector = BaseAction->getOffloadingDeviceKind() == Action::OFK_None;
2999 }
3000
3001 /// Check if a chain of actions can be combined and return the tool that can
3002 /// handle the combination of actions. The pointer to the current inputs \a
3003 /// Inputs and the list of offload actions \a CollapsedOffloadActions
3004 /// connected to collapsed actions are updated accordingly. The latter enables
3005 /// the caller of the selector to process them afterwards instead of just
3006 /// dropping them. If no suitable tool is found, null will be returned.
3007 const Tool *getTool(const ActionList *&Inputs,
3008 ActionList &CollapsedOffloadAction) {
3009 //
3010 // Get the largest chain of actions that we could combine.
3011 //
3012
3013 SmallVector<JobActionInfo, 5> ActionChain(1);
3014 ActionChain.back().JA = BaseAction;
3015 while (ActionChain.back().JA) {
3016 const Action *CurAction = ActionChain.back().JA;
3017
3018 // Grow the chain by one element.
3019 ActionChain.resize(ActionChain.size() + 1);
3020 JobActionInfo &AI = ActionChain.back();
3021
3022 // Attempt to fill it with the
3023 AI.JA =
3024 getPrevDependentAction(CurAction->getInputs(), AI.SavedOffloadAction);
Daniel Dunbarc4343942010-02-03 03:07:56 +00003025 }
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00003026
3027 // Pop the last action info as it could not be filled.
3028 ActionChain.pop_back();
3029
3030 //
3031 // Attempt to combine actions. If all combining attempts failed, just return
3032 // the tool of the provided action. At the end we attempt to combine the
3033 // action with any preprocessor action it may depend on.
3034 //
3035
3036 const Tool *T = combineAssembleBackendCompile(ActionChain, Inputs,
3037 CollapsedOffloadAction);
3038 if (!T)
3039 T = combineAssembleBackend(ActionChain, Inputs, CollapsedOffloadAction);
3040 if (!T)
3041 T = combineBackendCompile(ActionChain, Inputs, CollapsedOffloadAction);
3042 if (!T) {
3043 Inputs = &BaseAction->getInputs();
3044 T = TC.SelectTool(*BaseAction);
3045 }
3046
3047 combineWithPreprocessor(T, Inputs, CollapsedOffloadAction);
3048 return T;
Daniel Dunbarc4343942010-02-03 03:07:56 +00003049 }
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00003050};
Daniel Dunbarc4343942010-02-03 03:07:56 +00003051}
3052
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003053/// Return a string that uniquely identifies the result of a job. The bound arch
3054/// is not necessarily represented in the toolchain's triple -- for example,
3055/// armv7 and armv7s both map to the same triple -- so we need both in our map.
3056/// Also, we need to add the offloading device kind, as the same tool chain can
3057/// be used for host and device for some programming models, e.g. OpenMP.
3058static std::string GetTriplePlusArchString(const ToolChain *TC,
3059 StringRef BoundArch,
3060 Action::OffloadKind OffloadKind) {
Justin Lebar55c83322016-01-16 03:30:08 +00003061 std::string TriplePlusArch = TC->getTriple().normalize();
Mehdi Aminic50b1a22016-10-07 21:27:26 +00003062 if (!BoundArch.empty()) {
Justin Lebar55c83322016-01-16 03:30:08 +00003063 TriplePlusArch += "-";
3064 TriplePlusArch += BoundArch;
3065 }
Samuel Antao59efaed2016-10-27 17:31:22 +00003066 TriplePlusArch += "-";
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003067 TriplePlusArch += Action::GetOffloadKindName(OffloadKind);
3068 return TriplePlusArch;
3069}
3070
3071InputInfo Driver::BuildJobsForAction(
3072 Compilation &C, const Action *A, const ToolChain *TC, StringRef BoundArch,
3073 bool AtTopLevel, bool MultipleArchs, const char *LinkingOutput,
3074 std::map<std::pair<const Action *, std::string>, InputInfo> &CachedResults,
3075 Action::OffloadKind TargetDeviceOffloadKind) const {
3076 std::pair<const Action *, std::string> ActionTC = {
3077 A, GetTriplePlusArchString(TC, BoundArch, TargetDeviceOffloadKind)};
Justin Lebarb44f6fe2016-01-14 21:41:21 +00003078 auto CachedResult = CachedResults.find(ActionTC);
3079 if (CachedResult != CachedResults.end()) {
3080 return CachedResult->second;
3081 }
Samuel Antaod06239d2016-07-15 23:13:27 +00003082 InputInfo Result = BuildJobsForActionNoCache(
3083 C, A, TC, BoundArch, AtTopLevel, MultipleArchs, LinkingOutput,
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003084 CachedResults, TargetDeviceOffloadKind);
Justin Lebarb44f6fe2016-01-14 21:41:21 +00003085 CachedResults[ActionTC] = Result;
3086 return Result;
3087}
3088
3089InputInfo Driver::BuildJobsForActionNoCache(
Mehdi Aminic50b1a22016-10-07 21:27:26 +00003090 Compilation &C, const Action *A, const ToolChain *TC, StringRef BoundArch,
Justin Lebarb44f6fe2016-01-14 21:41:21 +00003091 bool AtTopLevel, bool MultipleArchs, const char *LinkingOutput,
Samuel Antaod06239d2016-07-15 23:13:27 +00003092 std::map<std::pair<const Action *, std::string>, InputInfo> &CachedResults,
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003093 Action::OffloadKind TargetDeviceOffloadKind) const {
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00003094 llvm::PrettyStackTraceString CrashInfo("Building compilation jobs");
Daniel Dunbarc4acf9d2009-03-18 23:18:19 +00003095
Samuel Antaod06239d2016-07-15 23:13:27 +00003096 InputInfoList OffloadDependencesInputInfo;
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003097 bool BuildingForOffloadDevice = TargetDeviceOffloadKind != Action::OFK_None;
Samuel Antaod06239d2016-07-15 23:13:27 +00003098 if (const OffloadAction *OA = dyn_cast<OffloadAction>(A)) {
3099 // The offload action is expected to be used in four different situations.
3100 //
3101 // a) Set a toolchain/architecture/kind for a host action:
3102 // Host Action 1 -> OffloadAction -> Host Action 2
3103 //
3104 // b) Set a toolchain/architecture/kind for a device action;
3105 // Device Action 1 -> OffloadAction -> Device Action 2
3106 //
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00003107 // c) Specify a device dependence to a host action;
Samuel Antaod06239d2016-07-15 23:13:27 +00003108 // Device Action 1 _
3109 // \
3110 // Host Action 1 ---> OffloadAction -> Host Action 2
3111 //
3112 // d) Specify a host dependence to a device action.
3113 // Host Action 1 _
3114 // \
3115 // Device Action 1 ---> OffloadAction -> Device Action 2
3116 //
3117 // For a) and b), we just return the job generated for the dependence. For
3118 // c) and d) we override the current action with the host/device dependence
3119 // if the current toolchain is host/device and set the offload dependences
3120 // info with the jobs obtained from the device/host dependence(s).
3121
3122 // If there is a single device option, just generate the job for it.
3123 if (OA->hasSingleDeviceDependence()) {
3124 InputInfo DevA;
3125 OA->doOnEachDeviceDependence([&](Action *DepA, const ToolChain *DepTC,
3126 const char *DepBoundArch) {
3127 DevA =
3128 BuildJobsForAction(C, DepA, DepTC, DepBoundArch, AtTopLevel,
3129 /*MultipleArchs*/ !!DepBoundArch, LinkingOutput,
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003130 CachedResults, DepA->getOffloadingDeviceKind());
Samuel Antaod06239d2016-07-15 23:13:27 +00003131 });
3132 return DevA;
Artem Belevich0ff05cd2015-07-13 23:27:56 +00003133 }
Samuel Antaod06239d2016-07-15 23:13:27 +00003134
3135 // If 'Action 2' is host, we generate jobs for the device dependences and
3136 // override the current action with the host dependence. Otherwise, we
3137 // generate the host dependences and override the action with the device
3138 // dependence. The dependences can't therefore be a top-level action.
3139 OA->doOnEachDependence(
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003140 /*IsHostDependence=*/BuildingForOffloadDevice,
Samuel Antaod06239d2016-07-15 23:13:27 +00003141 [&](Action *DepA, const ToolChain *DepTC, const char *DepBoundArch) {
3142 OffloadDependencesInputInfo.push_back(BuildJobsForAction(
3143 C, DepA, DepTC, DepBoundArch, /*AtTopLevel=*/false,
3144 /*MultipleArchs*/ !!DepBoundArch, LinkingOutput, CachedResults,
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003145 DepA->getOffloadingDeviceKind()));
Samuel Antaod06239d2016-07-15 23:13:27 +00003146 });
3147
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003148 A = BuildingForOffloadDevice
Samuel Antaod06239d2016-07-15 23:13:27 +00003149 ? OA->getSingleDeviceDependence(/*DoNotConsiderHostActions=*/true)
3150 : OA->getHostDependence();
Artem Belevich0ff05cd2015-07-13 23:27:56 +00003151 }
3152
Daniel Dunbare75d8342009-03-16 06:56:51 +00003153 if (const InputAction *IA = dyn_cast<InputAction>(A)) {
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00003154 // FIXME: It would be nice to not claim this here; maybe the old scheme of
3155 // just using Args was better?
Daniel Dunbar5cdf3e02009-03-19 07:29:38 +00003156 const Arg &Input = IA->getInputArg();
3157 Input.claim();
Daniel Dunbar35cbfeb2010-06-09 22:31:08 +00003158 if (Input.getOption().matches(options::OPT_INPUT)) {
Richard Smithbd55daf2012-11-01 04:30:05 +00003159 const char *Name = Input.getValue();
Justin Lebard98cea82016-01-11 23:15:21 +00003160 return InputInfo(A, Name, /* BaseInput = */ Name);
Douglas Katzman678d0cb2015-06-16 18:01:24 +00003161 }
Justin Lebard98cea82016-01-11 23:15:21 +00003162 return InputInfo(A, &Input, /* BaseInput = */ "");
Daniel Dunbare75d8342009-03-16 06:56:51 +00003163 }
3164
3165 if (const BindArchAction *BAA = dyn_cast<BindArchAction>(A)) {
Chad Rosiera78a6eb2012-04-27 16:50:38 +00003166 const ToolChain *TC;
Mehdi Aminic50b1a22016-10-07 21:27:26 +00003167 StringRef ArchName = BAA->getArchName();
Daniel Dunbar1ef3f2a2009-09-08 23:37:19 +00003168
Mehdi Aminic50b1a22016-10-07 21:27:26 +00003169 if (!ArchName.empty())
Andrey Turetskiy6a8b91d2016-04-21 10:16:48 +00003170 TC = &getToolChain(C.getArgs(),
3171 computeTargetTriple(*this, DefaultTargetTriple,
3172 C.getArgs(), ArchName));
Chad Rosiera78a6eb2012-04-27 16:50:38 +00003173 else
3174 TC = &C.getDefaultToolChain();
Daniel Dunbar1ef3f2a2009-09-08 23:37:19 +00003175
Nico Weber5a459f82016-02-23 19:30:43 +00003176 return BuildJobsForAction(C, *BAA->input_begin(), TC, ArchName, AtTopLevel,
Samuel Antaod06239d2016-07-15 23:13:27 +00003177 MultipleArchs, LinkingOutput, CachedResults,
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003178 TargetDeviceOffloadKind);
Daniel Dunbare75d8342009-03-16 06:56:51 +00003179 }
3180
Artem Belevich0ff05cd2015-07-13 23:27:56 +00003181
Daniel Dunbare75d8342009-03-16 06:56:51 +00003182 const ActionList *Inputs = &A->getInputs();
Daniel Dunbarc4343942010-02-03 03:07:56 +00003183
3184 const JobAction *JA = cast<JobAction>(A);
Samuel Antaod06239d2016-07-15 23:13:27 +00003185 ActionList CollapsedOffloadActions;
3186
Steven Wu844ab6a2016-11-16 06:06:44 +00003187 ToolSelector TS(JA, *TC, C, isSaveTempsEnabled(), embedBitcodeInObject());
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00003188 const Tool *T = TS.getTool(Inputs, CollapsedOffloadActions);
3189
Rafael Espindola79764462013-03-24 15:06:53 +00003190 if (!T)
Justin Lebar9eaa4892016-01-11 23:09:32 +00003191 return InputInfo();
Daniel Dunbare75d8342009-03-16 06:56:51 +00003192
Samuel Antaod06239d2016-07-15 23:13:27 +00003193 // If we've collapsed action list that contained OffloadAction we
3194 // need to build jobs for host/device-side inputs it may have held.
3195 for (const auto *OA : CollapsedOffloadActions)
3196 cast<OffloadAction>(OA)->doOnEachDependence(
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003197 /*IsHostDependence=*/BuildingForOffloadDevice,
Samuel Antaod06239d2016-07-15 23:13:27 +00003198 [&](Action *DepA, const ToolChain *DepTC, const char *DepBoundArch) {
3199 OffloadDependencesInputInfo.push_back(BuildJobsForAction(
Artem Belevichbee2f412016-08-22 18:50:34 +00003200 C, DepA, DepTC, DepBoundArch, /* AtTopLevel */ false,
Samuel Antaod06239d2016-07-15 23:13:27 +00003201 /*MultipleArchs=*/!!DepBoundArch, LinkingOutput, CachedResults,
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003202 DepA->getOffloadingDeviceKind()));
Samuel Antaod06239d2016-07-15 23:13:27 +00003203 });
Artem Belevichf8144ab2015-08-27 18:10:41 +00003204
Daniel Dunbare75d8342009-03-16 06:56:51 +00003205 // Only use pipes when there is exactly one input.
Daniel Dunbar1a093d22009-03-18 06:00:36 +00003206 InputInfoList InputInfos;
Saleem Abdulrasoolda3f4e52014-12-29 21:02:47 +00003207 for (const Action *Input : *Inputs) {
Eric Christopher14668dd2013-02-18 00:38:25 +00003208 // Treat dsymutil and verify sub-jobs as being at the top-level too, they
3209 // shouldn't get temporary output names.
Daniel Dunbar6beaf512010-06-04 18:28:41 +00003210 // FIXME: Clean this up.
Justin Lebar9eaa4892016-01-11 23:09:32 +00003211 bool SubJobAtTopLevel =
3212 AtTopLevel && (isa<DsymutilJobAction>(A) || isa<VerifyJobAction>(A));
Samuel Antaod06239d2016-07-15 23:13:27 +00003213 InputInfos.push_back(BuildJobsForAction(
3214 C, Input, TC, BoundArch, SubJobAtTopLevel, MultipleArchs, LinkingOutput,
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003215 CachedResults, A->getOffloadingDeviceKind()));
Daniel Dunbare75d8342009-03-16 06:56:51 +00003216 }
3217
Daniel Dunbare75d8342009-03-16 06:56:51 +00003218 // Always use the first input as the base input.
3219 const char *BaseInput = InputInfos[0].getBaseInput();
Daniel Dunbar7a178a42009-03-17 17:53:55 +00003220
Daniel Dunbar6beaf512010-06-04 18:28:41 +00003221 // ... except dsymutil actions, which use their actual input as the base
3222 // input.
3223 if (JA->getType() == types::TY_dSYM)
3224 BaseInput = InputInfos[0].getFilename();
3225
Samuel Antaod06239d2016-07-15 23:13:27 +00003226 // Append outputs of offload device jobs to the input list
3227 if (!OffloadDependencesInputInfo.empty())
3228 InputInfos.append(OffloadDependencesInputInfo.begin(),
3229 OffloadDependencesInputInfo.end());
Artem Belevich0ff05cd2015-07-13 23:27:56 +00003230
Vedant Kumar18286cf2016-07-27 23:02:20 +00003231 // Set the effective triple of the toolchain for the duration of this job.
3232 llvm::Triple EffectiveTriple;
3233 const ToolChain &ToolTC = T->getToolChain();
Samuel Antao31fef982016-10-27 17:39:44 +00003234 const ArgList &Args =
3235 C.getArgsForToolChain(TC, BoundArch, A->getOffloadingDeviceKind());
Vedant Kumar18286cf2016-07-27 23:02:20 +00003236 if (InputInfos.size() != 1) {
3237 EffectiveTriple = llvm::Triple(ToolTC.ComputeEffectiveClangTriple(Args));
3238 } else {
3239 // Pass along the input type if it can be unambiguously determined.
3240 EffectiveTriple = llvm::Triple(
3241 ToolTC.ComputeEffectiveClangTriple(Args, InputInfos[0].getType()));
3242 }
3243 RegisterEffectiveTriple TripleRAII(ToolTC, EffectiveTriple);
3244
Daniel Dunbard00272f2010-08-02 02:38:15 +00003245 // Determine the place to write output to, if any.
Justin Lebar9eaa4892016-01-11 23:09:32 +00003246 InputInfo Result;
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003247 InputInfoList UnbundlingResults;
3248 if (auto *UA = dyn_cast<OffloadUnbundlingJobAction>(JA)) {
3249 // If we have an unbundling job, we need to create results for all the
3250 // outputs. We also update the results cache so that other actions using
3251 // this unbundling action can get the right results.
3252 for (auto &UI : UA->getDependentActionsInfo()) {
3253 assert(UI.DependentOffloadKind != Action::OFK_None &&
3254 "Unbundling with no offloading??");
3255
3256 // Unbundling actions are never at the top level. When we generate the
3257 // offloading prefix, we also do that for the host file because the
3258 // unbundling action does not change the type of the output which can
3259 // cause a overwrite.
3260 std::string OffloadingPrefix = Action::GetOffloadingFileNamePrefix(
3261 UI.DependentOffloadKind,
3262 UI.DependentToolChain->getTriple().normalize(),
3263 /*CreatePrefixForHost=*/true);
3264 auto CurI = InputInfo(
3265 UA, GetNamedOutputPath(C, *UA, BaseInput, UI.DependentBoundArch,
3266 /*AtTopLevel=*/false, MultipleArchs,
3267 OffloadingPrefix),
3268 BaseInput);
3269 // Save the unbundling result.
3270 UnbundlingResults.push_back(CurI);
3271
3272 // Get the unique string identifier for this dependence and cache the
3273 // result.
3274 CachedResults[{A, GetTriplePlusArchString(
3275 UI.DependentToolChain, UI.DependentBoundArch,
3276 UI.DependentOffloadKind)}] = CurI;
3277 }
3278
3279 // Now that we have all the results generated, select the one that should be
3280 // returned for the current depending action.
3281 std::pair<const Action *, std::string> ActionTC = {
3282 A, GetTriplePlusArchString(TC, BoundArch, TargetDeviceOffloadKind)};
3283 assert(CachedResults.find(ActionTC) != CachedResults.end() &&
3284 "Result does not exist??");
3285 Result = CachedResults[ActionTC];
3286 } else if (JA->getType() == types::TY_Nothing)
Justin Lebard98cea82016-01-11 23:15:21 +00003287 Result = InputInfo(A, BaseInput);
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003288 else {
3289 // We only have to generate a prefix for the host if this is not a top-level
3290 // action.
3291 std::string OffloadingPrefix = Action::GetOffloadingFileNamePrefix(
3292 A->getOffloadingDeviceKind(), TC->getTriple().normalize(),
3293 /*CreatePrefixForHost=*/!!A->getOffloadingHostActiveKinds() &&
3294 !AtTopLevel);
Justin Lebard98cea82016-01-11 23:15:21 +00003295 Result = InputInfo(A, GetNamedOutputPath(C, *JA, BaseInput, BoundArch,
Samuel Antaod06239d2016-07-15 23:13:27 +00003296 AtTopLevel, MultipleArchs,
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003297 OffloadingPrefix),
Justin Lebard98cea82016-01-11 23:15:21 +00003298 BaseInput);
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003299 }
Daniel Dunbar7a178a42009-03-17 17:53:55 +00003300
Chad Rosierbe10f982011-08-02 17:58:04 +00003301 if (CCCPrintBindings && !CCGenDiagnostics) {
Rafael Espindola79764462013-03-24 15:06:53 +00003302 llvm::errs() << "# \"" << T->getToolChain().getTripleString() << '"'
3303 << " - \"" << T->getName() << "\", inputs: [";
Daniel Dunbarb39cc522009-03-17 22:47:06 +00003304 for (unsigned i = 0, e = InputInfos.size(); i != e; ++i) {
3305 llvm::errs() << InputInfos[i].getAsString();
3306 if (i + 1 != e)
3307 llvm::errs() << ", ";
3308 }
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003309 if (UnbundlingResults.empty())
3310 llvm::errs() << "], output: " << Result.getAsString() << "\n";
3311 else {
3312 llvm::errs() << "], outputs: [";
3313 for (unsigned i = 0, e = UnbundlingResults.size(); i != e; ++i) {
3314 llvm::errs() << UnbundlingResults[i].getAsString();
3315 if (i + 1 != e)
3316 llvm::errs() << ", ";
3317 }
3318 llvm::errs() << "] \n";
3319 }
Daniel Dunbarb39cc522009-03-17 22:47:06 +00003320 } else {
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003321 if (UnbundlingResults.empty())
3322 T->ConstructJob(
3323 C, *JA, Result, InputInfos,
3324 C.getArgsForToolChain(TC, BoundArch, JA->getOffloadingDeviceKind()),
3325 LinkingOutput);
3326 else
Samuel Antao7108bf32016-11-03 15:41:50 +00003327 T->ConstructJobMultipleOutputs(
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003328 C, *JA, UnbundlingResults, InputInfos,
3329 C.getArgsForToolChain(TC, BoundArch, JA->getOffloadingDeviceKind()),
3330 LinkingOutput);
Daniel Dunbarb39cc522009-03-17 22:47:06 +00003331 }
Justin Lebar9eaa4892016-01-11 23:09:32 +00003332 return Result;
Daniel Dunbare75d8342009-03-16 06:56:51 +00003333}
3334
Hans Wennborga7707222015-01-09 17:38:53 +00003335const char *Driver::getDefaultImageName() const {
3336 llvm::Triple Target(llvm::Triple::normalize(DefaultTargetTriple));
3337 return Target.isOSWindows() ? "a.exe" : "a.out";
3338}
3339
Hans Wennborg2c21f742013-10-17 16:16:23 +00003340/// \brief Create output filename based on ArgValue, which could either be a
3341/// full filename, filename without extension, or a directory. If ArgValue
3342/// does not provide a filename, then use BaseName, and use the extension
3343/// suitable for FileType.
Hans Wennborg207fcf02013-08-12 21:56:42 +00003344static const char *MakeCLOutputFilename(const ArgList &Args, StringRef ArgValue,
Douglas Katzmana67e50c2015-06-26 15:47:46 +00003345 StringRef BaseName,
3346 types::ID FileType) {
Hans Wennborg207fcf02013-08-12 21:56:42 +00003347 SmallString<128> Filename = ArgValue;
Justin Bogner5aaf2e72014-06-26 20:59:36 +00003348
Hans Wennborgf1a74252013-09-10 20:18:04 +00003349 if (ArgValue.empty()) {
3350 // If the argument is empty, output to BaseName in the current dir.
3351 Filename = BaseName;
3352 } else if (llvm::sys::path::is_separator(Filename.back())) {
Hans Wennborg207fcf02013-08-12 21:56:42 +00003353 // If the argument is a directory, output to BaseName in that dir.
3354 llvm::sys::path::append(Filename, BaseName);
3355 }
3356
3357 if (!llvm::sys::path::has_extension(ArgValue)) {
3358 // If the argument didn't provide an extension, then set it.
3359 const char *Extension = types::getTypeTempSuffix(FileType, true);
Hans Wennborgf1a74252013-09-10 20:18:04 +00003360
3361 if (FileType == types::TY_Image &&
3362 Args.hasArg(options::OPT__SLASH_LD, options::OPT__SLASH_LDd)) {
3363 // The output file is a dll.
3364 Extension = "dll";
3365 }
3366
Hans Wennborg207fcf02013-08-12 21:56:42 +00003367 llvm::sys::path::replace_extension(Filename, Extension);
3368 }
3369
3370 return Args.MakeArgString(Filename.c_str());
3371}
3372
Douglas Katzmana67e50c2015-06-26 15:47:46 +00003373const char *Driver::GetNamedOutputPath(Compilation &C, const JobAction &JA,
Daniel Dunbar7a178a42009-03-17 17:53:55 +00003374 const char *BaseInput,
Mehdi Aminic50b1a22016-10-07 21:27:26 +00003375 StringRef BoundArch, bool AtTopLevel,
Samuel Antaod06239d2016-07-15 23:13:27 +00003376 bool MultipleArchs,
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003377 StringRef OffloadingPrefix) const {
Daniel Dunbar2608c542009-03-18 01:38:48 +00003378 llvm::PrettyStackTraceString CrashInfo("Computing output path");
Daniel Dunbar7a178a42009-03-17 17:53:55 +00003379 // Output to a user requested destination?
Douglas Katzmana67e50c2015-06-26 15:47:46 +00003380 if (AtTopLevel && !isa<DsymutilJobAction>(JA) && !isa<VerifyJobAction>(JA)) {
Daniel Dunbar7a178a42009-03-17 17:53:55 +00003381 if (Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o))
Chad Rosier633dcdc2013-01-24 19:14:47 +00003382 return C.addResultFile(FinalOutput->getValue(), &JA);
Daniel Dunbar7a178a42009-03-17 17:53:55 +00003383 }
3384
Hans Wennborge0053472013-12-20 18:40:46 +00003385 // For /P, preprocess to file named after BaseInput.
3386 if (C.getArgs().hasArg(options::OPT__SLASH_P)) {
3387 assert(AtTopLevel && isa<PreprocessJobAction>(JA));
3388 StringRef BaseName = llvm::sys::path::filename(BaseInput);
Hans Wennborg04c764f2014-06-17 00:19:12 +00003389 StringRef NameArg;
Greg Bedwell065f70a2015-06-09 10:24:06 +00003390 if (Arg *A = C.getArgs().getLastArg(options::OPT__SLASH_Fi))
Hans Wennborg04c764f2014-06-17 00:19:12 +00003391 NameArg = A->getValue();
Douglas Katzmana67e50c2015-06-26 15:47:46 +00003392 return C.addResultFile(
3393 MakeCLOutputFilename(C.getArgs(), NameArg, BaseName, types::TY_PP_C),
3394 &JA);
Hans Wennborge0053472013-12-20 18:40:46 +00003395 }
3396
Nick Lewycky6e1ce292010-09-24 00:46:53 +00003397 // Default to writing to stdout?
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +00003398 if (AtTopLevel && !CCGenDiagnostics &&
3399 (isa<PreprocessJobAction>(JA) || JA.getType() == types::TY_ModuleFile))
Nick Lewycky6e1ce292010-09-24 00:46:53 +00003400 return "-";
3401
Hans Wennborg2c21f742013-10-17 16:16:23 +00003402 // Is this the assembly listing for /FA?
3403 if (JA.getType() == types::TY_PP_Asm &&
3404 (C.getArgs().hasArg(options::OPT__SLASH_FA) ||
3405 C.getArgs().hasArg(options::OPT__SLASH_Fa))) {
3406 // Use /Fa and the input filename to determine the asm file name.
3407 StringRef BaseName = llvm::sys::path::filename(BaseInput);
3408 StringRef FaValue = C.getArgs().getLastArgValue(options::OPT__SLASH_Fa);
Douglas Katzmana67e50c2015-06-26 15:47:46 +00003409 return C.addResultFile(
3410 MakeCLOutputFilename(C.getArgs(), FaValue, BaseName, JA.getType()),
3411 &JA);
Hans Wennborg2c21f742013-10-17 16:16:23 +00003412 }
3413
Daniel Dunbar7a178a42009-03-17 17:53:55 +00003414 // Output to a temporary file?
Reid Kleckner68eb60b2015-02-02 22:41:48 +00003415 if ((!AtTopLevel && !isSaveTempsEnabled() &&
Douglas Katzmana67e50c2015-06-26 15:47:46 +00003416 !C.getArgs().hasArg(options::OPT__SLASH_Fo)) ||
Chad Rosierbe10f982011-08-02 17:58:04 +00003417 CCGenDiagnostics) {
Chad Rosier97c37372011-08-26 22:27:02 +00003418 StringRef Name = llvm::sys::path::filename(BaseInput);
3419 std::pair<StringRef, StringRef> Split = Name.split('.');
Douglas Katzmana67e50c2015-06-26 15:47:46 +00003420 std::string TmpName = GetTemporaryPath(
3421 Split.first, types::getTypeTempSuffix(JA.getType(), IsCLMode()));
Malcolm Parsonsf76f6502016-11-02 10:39:27 +00003422 return C.addTempFile(C.getArgs().MakeArgString(TmpName));
Daniel Dunbar7a178a42009-03-17 17:53:55 +00003423 }
3424
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00003425 SmallString<128> BasePath(BaseInput);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003426 StringRef BaseName;
Daniel Dunbar67fea712011-03-25 18:16:51 +00003427
3428 // Dsymutil actions should use the full path.
Eric Christopher551ef452011-08-23 17:56:55 +00003429 if (isa<DsymutilJobAction>(JA) || isa<VerifyJobAction>(JA))
Daniel Dunbar67fea712011-03-25 18:16:51 +00003430 BaseName = BasePath;
3431 else
3432 BaseName = llvm::sys::path::filename(BasePath);
Daniel Dunbar7a178a42009-03-17 17:53:55 +00003433
3434 // Determine what the derived output name should be.
3435 const char *NamedOutput;
Hans Wennborg2b89a262013-08-06 22:11:28 +00003436
Hans Wennborg625fba82016-10-04 21:01:04 +00003437 if ((JA.getType() == types::TY_Object || JA.getType() == types::TY_LTO_BC) &&
Ehsan Akhgari81f36b72014-09-11 18:16:21 +00003438 C.getArgs().hasArg(options::OPT__SLASH_Fo, options::OPT__SLASH_o)) {
3439 // The /Fo or /o flag decides the object filename.
Douglas Katzmana67e50c2015-06-26 15:47:46 +00003440 StringRef Val =
3441 C.getArgs()
3442 .getLastArg(options::OPT__SLASH_Fo, options::OPT__SLASH_o)
3443 ->getValue();
3444 NamedOutput =
3445 MakeCLOutputFilename(C.getArgs(), Val, BaseName, types::TY_Object);
Hans Wennborg207fcf02013-08-12 21:56:42 +00003446 } else if (JA.getType() == types::TY_Image &&
Douglas Katzmana67e50c2015-06-26 15:47:46 +00003447 C.getArgs().hasArg(options::OPT__SLASH_Fe,
3448 options::OPT__SLASH_o)) {
Ehsan Akhgari81f36b72014-09-11 18:16:21 +00003449 // The /Fe or /o flag names the linked file.
Douglas Katzmana67e50c2015-06-26 15:47:46 +00003450 StringRef Val =
3451 C.getArgs()
3452 .getLastArg(options::OPT__SLASH_Fe, options::OPT__SLASH_o)
3453 ->getValue();
3454 NamedOutput =
3455 MakeCLOutputFilename(C.getArgs(), Val, BaseName, types::TY_Image);
Hans Wennborgf1a74252013-09-10 20:18:04 +00003456 } else if (JA.getType() == types::TY_Image) {
Hans Wennborg207fcf02013-08-12 21:56:42 +00003457 if (IsCLMode()) {
3458 // clang-cl uses BaseName for the executable name.
Douglas Katzmana67e50c2015-06-26 15:47:46 +00003459 NamedOutput =
3460 MakeCLOutputFilename(C.getArgs(), "", BaseName, types::TY_Image);
Samuel Antao59efaed2016-10-27 17:31:22 +00003461 } else {
Hans Wennborga7707222015-01-09 17:38:53 +00003462 SmallString<128> Output(getDefaultImageName());
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003463 Output += OffloadingPrefix;
Samuel Antao59efaed2016-10-27 17:31:22 +00003464 if (MultipleArchs && !BoundArch.empty()) {
3465 Output += "-";
3466 Output.append(BoundArch);
3467 }
Chad Rosier35767232013-04-30 22:01:21 +00003468 NamedOutput = C.getArgs().MakeArgString(Output.c_str());
Nico Weber2ca4be92016-03-01 23:16:44 +00003469 }
3470 } else if (JA.getType() == types::TY_PCH && IsCLMode()) {
Malcolm Parsonsf76f6502016-11-02 10:39:27 +00003471 NamedOutput = C.getArgs().MakeArgString(GetClPchPath(C, BaseName));
Daniel Dunbar7a178a42009-03-17 17:53:55 +00003472 } else {
Hans Wennborg0a096a02013-09-05 17:05:56 +00003473 const char *Suffix = types::getTypeTempSuffix(JA.getType(), IsCLMode());
Daniel Dunbar7a178a42009-03-17 17:53:55 +00003474 assert(Suffix && "All types used for output should have a suffix.");
3475
3476 std::string::size_type End = std::string::npos;
3477 if (!types::appendSuffixForType(JA.getType()))
3478 End = BaseName.rfind('.');
Chad Rosier35767232013-04-30 22:01:21 +00003479 SmallString<128> Suffixed(BaseName.substr(0, End));
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003480 Suffixed += OffloadingPrefix;
Mehdi Aminic50b1a22016-10-07 21:27:26 +00003481 if (MultipleArchs && !BoundArch.empty()) {
Chad Rosier35767232013-04-30 22:01:21 +00003482 Suffixed += "-";
3483 Suffixed.append(BoundArch);
3484 }
Bob Wilson23a55f12014-12-21 07:00:00 +00003485 // When using both -save-temps and -emit-llvm, use a ".tmp.bc" suffix for
3486 // the unoptimized bitcode so that it does not get overwritten by the ".bc"
3487 // optimized bitcode output.
3488 if (!AtTopLevel && C.getArgs().hasArg(options::OPT_emit_llvm) &&
3489 JA.getType() == types::TY_LLVM_BC)
3490 Suffixed += ".tmp";
Daniel Dunbar7a178a42009-03-17 17:53:55 +00003491 Suffixed += '.';
3492 Suffixed += Suffix;
3493 NamedOutput = C.getArgs().MakeArgString(Suffixed.c_str());
3494 }
3495
Reid Kleckner68eb60b2015-02-02 22:41:48 +00003496 // Prepend object file path if -save-temps=obj
3497 if (!AtTopLevel && isSaveTempsObj() && C.getArgs().hasArg(options::OPT_o) &&
3498 JA.getType() != types::TY_PCH) {
3499 Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o);
3500 SmallString<128> TempPath(FinalOutput->getValue());
3501 llvm::sys::path::remove_filename(TempPath);
3502 StringRef OutputFileName = llvm::sys::path::filename(NamedOutput);
3503 llvm::sys::path::append(TempPath, OutputFileName);
3504 NamedOutput = C.getArgs().MakeArgString(TempPath.c_str());
3505 }
3506
Chad Rosier62135492012-07-09 17:31:28 +00003507 // If we're saving temps and the temp file conflicts with the input file,
Chad Rosier5b58af02012-04-20 20:05:08 +00003508 // then avoid overwriting input file.
Reid Kleckner68eb60b2015-02-02 22:41:48 +00003509 if (!AtTopLevel && isSaveTempsEnabled() && NamedOutput == BaseName) {
Chad Rosier5b58af02012-04-20 20:05:08 +00003510 bool SameFile = false;
3511 SmallString<256> Result;
3512 llvm::sys::fs::current_path(Result);
3513 llvm::sys::path::append(Result, BaseName);
3514 llvm::sys::fs::equivalent(BaseInput, Result.c_str(), SameFile);
3515 // Must share the same path to conflict.
3516 if (SameFile) {
3517 StringRef Name = llvm::sys::path::filename(BaseInput);
3518 std::pair<StringRef, StringRef> Split = Name.split('.');
Douglas Katzmana67e50c2015-06-26 15:47:46 +00003519 std::string TmpName = GetTemporaryPath(
3520 Split.first, types::getTypeTempSuffix(JA.getType(), IsCLMode()));
Malcolm Parsonsf76f6502016-11-02 10:39:27 +00003521 return C.addTempFile(C.getArgs().MakeArgString(TmpName));
Chad Rosier5b58af02012-04-20 20:05:08 +00003522 }
Chad Rosierf8412cd2011-07-15 21:54:29 +00003523 }
3524
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00003525 // As an annoying special case, PCH generation doesn't strip the pathname.
Nico Weber8ab92192016-03-02 23:29:29 +00003526 if (JA.getType() == types::TY_PCH && !IsCLMode()) {
Michael J. Spencere1696752010-12-18 00:19:12 +00003527 llvm::sys::path::remove_filename(BasePath);
3528 if (BasePath.empty())
Daniel Dunbare6c83192009-03-18 09:58:30 +00003529 BasePath = NamedOutput;
3530 else
Michael J. Spencere1696752010-12-18 00:19:12 +00003531 llvm::sys::path::append(BasePath, NamedOutput);
Chad Rosier633dcdc2013-01-24 19:14:47 +00003532 return C.addResultFile(C.getArgs().MakeArgString(BasePath.c_str()), &JA);
Daniel Dunbar7a178a42009-03-17 17:53:55 +00003533 } else {
Chad Rosier633dcdc2013-01-24 19:14:47 +00003534 return C.addResultFile(NamedOutput, &JA);
Daniel Dunbar7a178a42009-03-17 17:53:55 +00003535 }
3536}
3537
Mehdi Amini12011172016-10-06 05:11:48 +00003538std::string Driver::GetFilePath(StringRef Name, const ToolChain &TC) const {
Chandler Carruth84559242010-03-22 01:52:07 +00003539 // Respect a limited subset of the '-Bprefix' functionality in GCC by
Logan Chiencd679fd2012-10-04 08:08:56 +00003540 // attempting to use this prefix when looking for file paths.
Douglas Katzman26eabf62015-06-24 15:10:30 +00003541 for (const std::string &Dir : PrefixDirs) {
Joerg Sonnenberger6165ab12011-03-21 13:51:29 +00003542 if (Dir.empty())
3543 continue;
Douglas Katzman26eabf62015-06-24 15:10:30 +00003544 SmallString<128> P(Dir[0] == '=' ? SysRoot + Dir.substr(1) : Dir);
Rafael Espindola609a6642013-06-24 18:33:43 +00003545 llvm::sys::path::append(P, Name);
3546 if (llvm::sys::fs::exists(Twine(P)))
Chandler Carruth84559242010-03-22 01:52:07 +00003547 return P.str();
3548 }
3549
Rafael Espindola609a6642013-06-24 18:33:43 +00003550 SmallString<128> P(ResourceDir);
3551 llvm::sys::path::append(P, Name);
3552 if (llvm::sys::fs::exists(Twine(P)))
Peter Collingbournefa9771f2011-09-06 02:08:31 +00003553 return P.str();
3554
Douglas Katzman26eabf62015-06-24 15:10:30 +00003555 for (const std::string &Dir : TC.getFilePaths()) {
Joerg Sonnenberger6165ab12011-03-21 13:51:29 +00003556 if (Dir.empty())
3557 continue;
Douglas Katzman26eabf62015-06-24 15:10:30 +00003558 SmallString<128> P(Dir[0] == '=' ? SysRoot + Dir.substr(1) : Dir);
Rafael Espindola609a6642013-06-24 18:33:43 +00003559 llvm::sys::path::append(P, Name);
3560 if (llvm::sys::fs::exists(Twine(P)))
Daniel Dunbar1ce81532009-09-09 22:33:00 +00003561 return P.str();
Daniel Dunbar68b01a02009-03-18 20:26:19 +00003562 }
3563
Daniel Dunbar1ce81532009-09-09 22:33:00 +00003564 return Name;
Daniel Dunbar5e0f6af2009-03-13 00:51:18 +00003565}
3566
Douglas Katzmana67e50c2015-06-26 15:47:46 +00003567void Driver::generatePrefixedToolNames(
Mehdi Amini12011172016-10-06 05:11:48 +00003568 StringRef Tool, const ToolChain &TC,
Douglas Katzmana67e50c2015-06-26 15:47:46 +00003569 SmallVectorImpl<std::string> &Names) const {
Saleem Abdulrasoolf0ba6ce2014-10-25 23:33:21 +00003570 // FIXME: Needs a better variable than DefaultTargetTriple
Mehdi Amini12011172016-10-06 05:11:48 +00003571 Names.emplace_back((DefaultTargetTriple + "-" + Tool).str());
Benjamin Kramer3204b152015-05-29 19:42:19 +00003572 Names.emplace_back(Tool);
Vasileios Kalintirisc744e122015-11-12 15:26:54 +00003573
3574 // Allow the discovery of tools prefixed with LLVM's default target triple.
3575 std::string LLVMDefaultTargetTriple = llvm::sys::getDefaultTargetTriple();
3576 if (LLVMDefaultTargetTriple != DefaultTargetTriple)
Mehdi Amini12011172016-10-06 05:11:48 +00003577 Names.emplace_back((LLVMDefaultTargetTriple + "-" + Tool).str());
Saleem Abdulrasoolf0ba6ce2014-10-25 23:33:21 +00003578}
3579
Benjamin Kramer7111b912014-11-04 20:26:01 +00003580static bool ScanDirForExecutable(SmallString<128> &Dir,
3581 ArrayRef<std::string> Names) {
Saleem Abdulrasoolf0ba6ce2014-10-25 23:33:21 +00003582 for (const auto &Name : Names) {
3583 llvm::sys::path::append(Dir, Name);
3584 if (llvm::sys::fs::can_execute(Twine(Dir)))
3585 return true;
3586 llvm::sys::path::remove_filename(Dir);
3587 }
3588 return false;
3589}
3590
Mehdi Amini12011172016-10-06 05:11:48 +00003591std::string Driver::GetProgramPath(StringRef Name, const ToolChain &TC) const {
Saleem Abdulrasoolf0ba6ce2014-10-25 23:33:21 +00003592 SmallVector<std::string, 2> TargetSpecificExecutables;
3593 generatePrefixedToolNames(Name, TC, TargetSpecificExecutables);
3594
Chandler Carruth84559242010-03-22 01:52:07 +00003595 // Respect a limited subset of the '-Bprefix' functionality in GCC by
Logan Chiencd679fd2012-10-04 08:08:56 +00003596 // attempting to use this prefix when looking for program paths.
Saleem Abdulrasool23d99b12014-09-16 03:48:32 +00003597 for (const auto &PrefixDir : PrefixDirs) {
3598 if (llvm::sys::fs::is_directory(PrefixDir)) {
3599 SmallString<128> P(PrefixDir);
Saleem Abdulrasoolf0ba6ce2014-10-25 23:33:21 +00003600 if (ScanDirForExecutable(P, TargetSpecificExecutables))
Rafael Espindola8be5c052013-06-19 13:24:29 +00003601 return P.str();
Simon Atanasyana47ba292012-10-31 14:39:28 +00003602 } else {
Mehdi Amini12011172016-10-06 05:11:48 +00003603 SmallString<128> P((PrefixDir + Name).str());
Rafael Espindola609a6642013-06-24 18:33:43 +00003604 if (llvm::sys::fs::can_execute(Twine(P)))
Rafael Espindola8be5c052013-06-19 13:24:29 +00003605 return P.str();
Simon Atanasyan86bdab72012-10-31 12:01:53 +00003606 }
Chandler Carruth84559242010-03-22 01:52:07 +00003607 }
3608
Daniel Dunbar68b01a02009-03-18 20:26:19 +00003609 const ToolChain::path_list &List = TC.getProgramPaths();
Saleem Abdulrasool23d99b12014-09-16 03:48:32 +00003610 for (const auto &Path : List) {
3611 SmallString<128> P(Path);
Saleem Abdulrasoolf0ba6ce2014-10-25 23:33:21 +00003612 if (ScanDirForExecutable(P, TargetSpecificExecutables))
Rafael Espindola8be5c052013-06-19 13:24:29 +00003613 return P.str();
Daniel Dunbar68b01a02009-03-18 20:26:19 +00003614 }
3615
Daniel Dunbar76ce7412009-03-23 16:15:50 +00003616 // If all else failed, search the path.
Michael J. Spencerb011d482014-11-07 21:30:32 +00003617 for (const auto &TargetSpecificExecutable : TargetSpecificExecutables)
3618 if (llvm::ErrorOr<std::string> P =
3619 llvm::sys::findProgramByName(TargetSpecificExecutable))
Michael J. Spencer04162ea2014-11-04 01:30:55 +00003620 return *P;
Daniel Dunbar6f668772009-03-18 21:34:08 +00003621
Daniel Dunbar1ce81532009-09-09 22:33:00 +00003622 return Name;
Daniel Dunbar5e0f6af2009-03-13 00:51:18 +00003623}
3624
Mehdi Amini12011172016-10-06 05:11:48 +00003625std::string Driver::GetTemporaryPath(StringRef Prefix, StringRef Suffix) const {
Rafael Espindola37d229d2013-06-25 04:26:55 +00003626 SmallString<128> Path;
Rafael Espindolac0809172014-06-12 14:02:15 +00003627 std::error_code EC = llvm::sys::fs::createTemporaryFile(Prefix, Suffix, Path);
Rafael Espindola37d229d2013-06-25 04:26:55 +00003628 if (EC) {
3629 Diag(clang::diag::err_unable_to_make_temp) << EC.message();
Daniel Dunbare627c1c2009-03-18 19:34:39 +00003630 return "";
3631 }
3632
Rafael Espindola37d229d2013-06-25 04:26:55 +00003633 return Path.str();
Daniel Dunbare627c1c2009-03-18 19:34:39 +00003634}
3635
Nico Weber2ca4be92016-03-01 23:16:44 +00003636std::string Driver::GetClPchPath(Compilation &C, StringRef BaseName) const {
3637 SmallString<128> Output;
3638 if (Arg *FpArg = C.getArgs().getLastArg(options::OPT__SLASH_Fp)) {
3639 // FIXME: If anybody needs it, implement this obscure rule:
3640 // "If you specify a directory without a file name, the default file name
3641 // is VCx0.pch., where x is the major version of Visual C++ in use."
3642 Output = FpArg->getValue();
3643
3644 // "If you do not specify an extension as part of the path name, an
3645 // extension of .pch is assumed. "
3646 if (!llvm::sys::path::has_extension(Output))
3647 Output += ".pch";
3648 } else {
3649 Output = BaseName;
3650 llvm::sys::path::replace_extension(Output, ".pch");
3651 }
3652 return Output.str();
3653}
3654
Chandler Carruth2ad5de12012-01-25 11:01:57 +00003655const ToolChain &Driver::getToolChain(const ArgList &Args,
Artem Belevich959e0542015-07-10 19:47:55 +00003656 const llvm::Triple &Target) const {
Chandler Carruth2ad5de12012-01-25 11:01:57 +00003657
Chandler Carruthd7fa2e02012-01-31 02:21:20 +00003658 ToolChain *&TC = ToolChains[Target.str()];
Chandler Carruth2ad5de12012-01-25 11:01:57 +00003659 if (!TC) {
3660 switch (Target.getOS()) {
Reid Kleckner330fb172016-05-11 16:19:05 +00003661 case llvm::Triple::Haiku:
3662 TC = new toolchains::Haiku(*this, Target, Args);
3663 break;
Ed Schouten3c3e58c2015-03-26 11:13:44 +00003664 case llvm::Triple::CloudABI:
3665 TC = new toolchains::CloudABI(*this, Target, Args);
3666 break;
Chandler Carruth2ad5de12012-01-25 11:01:57 +00003667 case llvm::Triple::Darwin:
3668 case llvm::Triple::MacOSX:
3669 case llvm::Triple::IOS:
Tim Northover6f3ff222015-10-30 16:30:27 +00003670 case llvm::Triple::TvOS:
3671 case llvm::Triple::WatchOS:
Rafael Espindola14627962013-11-24 23:28:23 +00003672 TC = new toolchains::DarwinClang(*this, Target, Args);
Chandler Carruth2ad5de12012-01-25 11:01:57 +00003673 break;
3674 case llvm::Triple::DragonFly:
Rafael Espindola1af7c212012-02-19 01:38:32 +00003675 TC = new toolchains::DragonFly(*this, Target, Args);
Chandler Carruth2ad5de12012-01-25 11:01:57 +00003676 break;
3677 case llvm::Triple::OpenBSD:
Rafael Espindola1af7c212012-02-19 01:38:32 +00003678 TC = new toolchains::OpenBSD(*this, Target, Args);
Chandler Carruth2ad5de12012-01-25 11:01:57 +00003679 break;
Eli Friedman9fa28852012-08-08 23:57:20 +00003680 case llvm::Triple::Bitrig:
3681 TC = new toolchains::Bitrig(*this, Target, Args);
3682 break;
Chandler Carruth2ad5de12012-01-25 11:01:57 +00003683 case llvm::Triple::NetBSD:
Rafael Espindola1af7c212012-02-19 01:38:32 +00003684 TC = new toolchains::NetBSD(*this, Target, Args);
Chandler Carruth2ad5de12012-01-25 11:01:57 +00003685 break;
3686 case llvm::Triple::FreeBSD:
Rafael Espindola1af7c212012-02-19 01:38:32 +00003687 TC = new toolchains::FreeBSD(*this, Target, Args);
Chandler Carruth2ad5de12012-01-25 11:01:57 +00003688 break;
3689 case llvm::Triple::Minix:
Rafael Espindola1af7c212012-02-19 01:38:32 +00003690 TC = new toolchains::Minix(*this, Target, Args);
Chandler Carruth2ad5de12012-01-25 11:01:57 +00003691 break;
3692 case llvm::Triple::Linux:
Andrey Turetskiy4798eb62016-06-16 10:36:09 +00003693 case llvm::Triple::ELFIAMCU:
Chandler Carruthcf705b22012-01-25 21:03:58 +00003694 if (Target.getArch() == llvm::Triple::hexagon)
Douglas Katzman54366072015-07-27 16:53:08 +00003695 TC = new toolchains::HexagonToolChain(*this, Target, Args);
Vasileios Kalintirisc744e122015-11-12 15:26:54 +00003696 else if ((Target.getVendor() == llvm::Triple::MipsTechnologies) &&
3697 !Target.hasEnvironment())
3698 TC = new toolchains::MipsLLVMToolChain(*this, Target, Args);
Chandler Carruthcf705b22012-01-25 21:03:58 +00003699 else
Rafael Espindola1af7c212012-02-19 01:38:32 +00003700 TC = new toolchains::Linux(*this, Target, Args);
Chandler Carruth2ad5de12012-01-25 11:01:57 +00003701 break;
Derek Schuff6ab52fa2015-03-30 20:31:33 +00003702 case llvm::Triple::NaCl:
Douglas Katzman54366072015-07-27 16:53:08 +00003703 TC = new toolchains::NaClToolChain(*this, Target, Args);
Derek Schuff6ab52fa2015-03-30 20:31:33 +00003704 break;
Petr Hosek62e1d232016-10-06 06:08:09 +00003705 case llvm::Triple::Fuchsia:
3706 TC = new toolchains::Fuchsia(*this, Target, Args);
3707 break;
David Chisnallf571cde2012-02-15 13:39:01 +00003708 case llvm::Triple::Solaris:
Rafael Espindola1af7c212012-02-19 01:38:32 +00003709 TC = new toolchains::Solaris(*this, Target, Args);
David Chisnallf571cde2012-02-15 13:39:01 +00003710 break;
Tom Stellard8fa33092015-07-18 01:49:05 +00003711 case llvm::Triple::AMDHSA:
3712 TC = new toolchains::AMDGPUToolChain(*this, Target, Args);
3713 break;
Chandler Carruth2ad5de12012-01-25 11:01:57 +00003714 case llvm::Triple::Win32:
Saleem Abdulrasool377066a2014-03-27 22:50:18 +00003715 switch (Target.getEnvironment()) {
3716 default:
3717 if (Target.isOSBinFormatELF())
3718 TC = new toolchains::Generic_ELF(*this, Target, Args);
3719 else if (Target.isOSBinFormatMachO())
3720 TC = new toolchains::MachO(*this, Target, Args);
3721 else
3722 TC = new toolchains::Generic_GCC(*this, Target, Args);
3723 break;
3724 case llvm::Triple::GNU:
Yaron Keren1c0070c2015-07-02 04:45:27 +00003725 TC = new toolchains::MinGW(*this, Target, Args);
Saleem Abdulrasool377066a2014-03-27 22:50:18 +00003726 break;
Saleem Abdulrasool543a78b2014-10-24 03:13:37 +00003727 case llvm::Triple::Itanium:
3728 TC = new toolchains::CrossWindowsToolChain(*this, Target, Args);
3729 break;
Saleem Abdulrasool377066a2014-03-27 22:50:18 +00003730 case llvm::Triple::MSVC:
3731 case llvm::Triple::UnknownEnvironment:
Saleem Abdulrasool819f3912014-10-22 02:37:29 +00003732 TC = new toolchains::MSVCToolChain(*this, Target, Args);
Saleem Abdulrasool377066a2014-03-27 22:50:18 +00003733 break;
3734 }
Chandler Carruth2ad5de12012-01-25 11:01:57 +00003735 break;
Filipe Cabecinhasc888e192015-10-14 12:25:43 +00003736 case llvm::Triple::PS4:
3737 TC = new toolchains::PS4CPU(*this, Target, Args);
3738 break;
David L Kreitzerd397ea42016-10-14 20:44:33 +00003739 case llvm::Triple::Contiki:
3740 TC = new toolchains::Contiki(*this, Target, Args);
3741 break;
Chandler Carruth2ad5de12012-01-25 11:01:57 +00003742 default:
Douglas Katzman9f5e70e2015-05-26 18:01:33 +00003743 // Of these targets, Hexagon is the only one that might have
3744 // an OS of Linux, in which case it got handled above already.
Douglas Katzman15a63ed2015-08-12 18:36:12 +00003745 switch (Target.getArch()) {
3746 case llvm::Triple::tce:
Rafael Espindola84b588b2013-03-18 18:10:27 +00003747 TC = new toolchains::TCEToolChain(*this, Target, Args);
Douglas Katzman15a63ed2015-08-12 18:36:12 +00003748 break;
Pekka Jaaskelainen67354482016-11-16 15:22:31 +00003749 case llvm::Triple::tcele:
3750 TC = new toolchains::TCELEToolChain(*this, Target, Args);
3751 break;
Douglas Katzman15a63ed2015-08-12 18:36:12 +00003752 case llvm::Triple::hexagon:
Douglas Katzman54366072015-07-27 16:53:08 +00003753 TC = new toolchains::HexagonToolChain(*this, Target, Args);
Douglas Katzman15a63ed2015-08-12 18:36:12 +00003754 break;
Jacques Pienaard964cc22016-03-28 21:02:54 +00003755 case llvm::Triple::lanai:
3756 TC = new toolchains::LanaiToolChain(*this, Target, Args);
3757 break;
Douglas Katzman15a63ed2015-08-12 18:36:12 +00003758 case llvm::Triple::xcore:
Douglas Katzman54366072015-07-27 16:53:08 +00003759 TC = new toolchains::XCoreToolChain(*this, Target, Args);
Douglas Katzman15a63ed2015-08-12 18:36:12 +00003760 break;
Dan Gohmanc2853072015-09-03 22:51:53 +00003761 case llvm::Triple::wasm32:
3762 case llvm::Triple::wasm64:
3763 TC = new toolchains::WebAssembly(*this, Target, Args);
3764 break;
Dylan McKay924fa3a2017-01-05 05:20:27 +00003765 case llvm::Triple::avr:
3766 TC = new toolchains::AVRToolChain(*this, Target, Args);
3767 break;
Douglas Katzman15a63ed2015-08-12 18:36:12 +00003768 default:
Douglas Katzmand6e597c2015-09-17 19:56:40 +00003769 if (Target.getVendor() == llvm::Triple::Myriad)
3770 TC = new toolchains::MyriadToolChain(*this, Target, Args);
3771 else if (Target.isOSBinFormatELF())
Douglas Katzman15a63ed2015-08-12 18:36:12 +00003772 TC = new toolchains::Generic_ELF(*this, Target, Args);
3773 else if (Target.isOSBinFormatMachO())
3774 TC = new toolchains::MachO(*this, Target, Args);
3775 else
3776 TC = new toolchains::Generic_GCC(*this, Target, Args);
3777 }
Chandler Carruth2ad5de12012-01-25 11:01:57 +00003778 }
3779 }
Justin Lebar66c4fd72016-11-18 00:41:22 +00003780
3781 // Intentionally omitted from the switch above: llvm::Triple::CUDA. CUDA
3782 // compiles always need two toolchains, the CUDA toolchain and the host
3783 // toolchain. So the only valid way to create a CUDA toolchain is via
3784 // CreateOffloadingDeviceToolChains.
3785
Chandler Carruth2ad5de12012-01-25 11:01:57 +00003786 return *TC;
Daniel Dunbar4dff6a42009-03-10 23:41:59 +00003787}
Daniel Dunbar8fa879d2009-03-24 18:57:02 +00003788
Rafael Espindola2f69d402013-03-18 15:33:26 +00003789bool Driver::ShouldUseClangCompiler(const JobAction &JA) const {
Douglas Katzman00249092015-06-12 15:45:21 +00003790 // Say "no" if there is not exactly one input of a type clang understands.
Nico Weber5a459f82016-02-23 19:30:43 +00003791 if (JA.size() != 1 ||
3792 !types::isAcceptedByClang((*JA.input_begin())->getType()))
Nick Lewycky5cc9ebb2012-11-15 05:36:36 +00003793 return false;
3794
Douglas Katzman00249092015-06-12 15:45:21 +00003795 // And say "no" if this is not a kind of action clang understands.
Nick Lewycky5cc9ebb2012-11-15 05:36:36 +00003796 if (!isa<PreprocessJobAction>(JA) && !isa<PrecompileJobAction>(JA) &&
Bob Wilson23a55f12014-12-21 07:00:00 +00003797 !isa<CompileJobAction>(JA) && !isa<BackendJobAction>(JA))
Nick Lewycky5cc9ebb2012-11-15 05:36:36 +00003798 return false;
3799
3800 return true;
3801}
3802
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00003803/// GetReleaseVersion - Parse (([0-9]+)(.([0-9]+)(.([0-9]+)?))?)? and return the
3804/// grouped values as integers. Numbers which are not provided are set to 0.
Daniel Dunbarc7fd57a2009-03-26 15:58:36 +00003805///
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00003806/// \return True if the entire string was parsed (9.2), or all groups were
3807/// parsed (10.3.5extrastuff).
Mehdi Amini12011172016-10-06 05:11:48 +00003808bool Driver::GetReleaseVersion(StringRef Str, unsigned &Major, unsigned &Minor,
3809 unsigned &Micro, bool &HadExtra) {
Daniel Dunbarc7fd57a2009-03-26 15:58:36 +00003810 HadExtra = false;
3811
3812 Major = Minor = Micro = 0;
Mehdi Amini12011172016-10-06 05:11:48 +00003813 if (Str.empty())
Bob Wilson433cb312015-04-07 01:03:35 +00003814 return false;
Daniel Dunbarc7fd57a2009-03-26 15:58:36 +00003815
Mehdi Amini12011172016-10-06 05:11:48 +00003816 if (Str.consumeInteger(10, Major))
3817 return false;
3818 if (Str.empty())
Daniel Dunbarc7fd57a2009-03-26 15:58:36 +00003819 return true;
Mehdi Amini12011172016-10-06 05:11:48 +00003820 if (Str[0] != '.')
Daniel Dunbarc7fd57a2009-03-26 15:58:36 +00003821 return false;
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00003822
Mehdi Amini12011172016-10-06 05:11:48 +00003823 Str = Str.drop_front(1);
Daniel Dunbarc7fd57a2009-03-26 15:58:36 +00003824
Mehdi Amini12011172016-10-06 05:11:48 +00003825 if (Str.consumeInteger(10, Minor))
Daniel Dunbarc7fd57a2009-03-26 15:58:36 +00003826 return false;
Mehdi Amini12011172016-10-06 05:11:48 +00003827 if (Str.empty())
3828 return true;
3829 if (Str[0] != '.')
3830 return false;
3831 Str = Str.drop_front(1);
3832
3833 if (Str.consumeInteger(10, Micro))
3834 return false;
3835 if (!Str.empty())
3836 HadExtra = true;
Daniel Dunbarc7fd57a2009-03-26 15:58:36 +00003837 return true;
3838}
Hans Wennborg6ddc6902013-07-27 00:23:45 +00003839
Bruno Cardoso Lopes8ed5cac2016-03-31 02:45:46 +00003840/// Parse digits from a string \p Str and fulfill \p Digits with
3841/// the parsed numbers. This method assumes that the max number of
3842/// digits to look for is equal to Digits.size().
3843///
3844/// \return True if the entire string was parsed and there are
3845/// no extra characters remaining at the end.
Mehdi Amini12011172016-10-06 05:11:48 +00003846bool Driver::GetReleaseVersion(StringRef Str,
Bruno Cardoso Lopes8ed5cac2016-03-31 02:45:46 +00003847 MutableArrayRef<unsigned> Digits) {
Mehdi Amini12011172016-10-06 05:11:48 +00003848 if (Str.empty())
Bruno Cardoso Lopes8ed5cac2016-03-31 02:45:46 +00003849 return false;
3850
Bruno Cardoso Lopes8ed5cac2016-03-31 02:45:46 +00003851 unsigned CurDigit = 0;
3852 while (CurDigit < Digits.size()) {
Mehdi Amini12011172016-10-06 05:11:48 +00003853 unsigned Digit;
3854 if (Str.consumeInteger(10, Digit))
Bruno Cardoso Lopes8ed5cac2016-03-31 02:45:46 +00003855 return false;
Mehdi Amini12011172016-10-06 05:11:48 +00003856 Digits[CurDigit] = Digit;
3857 if (Str.empty())
3858 return true;
3859 if (Str[0] != '.')
3860 return false;
3861 Str = Str.drop_front(1);
Bruno Cardoso Lopes8ed5cac2016-03-31 02:45:46 +00003862 CurDigit++;
3863 }
3864
3865 // More digits than requested, bail out...
3866 return false;
3867}
3868
Hans Wennborg6ddc6902013-07-27 00:23:45 +00003869std::pair<unsigned, unsigned> Driver::getIncludeExcludeOptionFlagMasks() const {
3870 unsigned IncludedFlagsBitmask = 0;
Rafael Espindolacc707bc2013-09-25 15:54:41 +00003871 unsigned ExcludedFlagsBitmask = options::NoDriverOption;
Hans Wennborg6ddc6902013-07-27 00:23:45 +00003872
3873 if (Mode == CLMode) {
Hans Wennborg19076102013-07-31 20:51:53 +00003874 // Include CL and Core options.
3875 IncludedFlagsBitmask |= options::CLOption;
3876 IncludedFlagsBitmask |= options::CoreOption;
Hans Wennborg6ddc6902013-07-27 00:23:45 +00003877 } else {
3878 ExcludedFlagsBitmask |= options::CLOption;
3879 }
3880
3881 return std::make_pair(IncludedFlagsBitmask, ExcludedFlagsBitmask);
3882}
Benjamin Kramerab88f622014-03-25 18:02:07 +00003883
Douglas Katzmanf08fadf2015-06-04 14:40:44 +00003884bool clang::driver::isOptimizationLevelFast(const ArgList &Args) {
Benjamin Kramerab88f622014-03-25 18:02:07 +00003885 return Args.hasFlag(options::OPT_Ofast, options::OPT_O_Group, false);
3886}