blob: 9e92f64f66078440814ea85503bc7566b8756e98 [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"
David L. Jonesf561aba2017-03-08 01:02:16 +000012#include "ToolChains/AMDGPU.h"
13#include "ToolChains/AVR.h"
Ed Schouten4dabea22017-06-25 08:29:09 +000014#include "ToolChains/Ananas.h"
Yaxun Liuf6144222018-05-30 00:53:50 +000015#include "ToolChains/BareMetal.h"
David L. Jonesf561aba2017-03-08 01:02:16 +000016#include "ToolChains/Clang.h"
17#include "ToolChains/CloudABI.h"
18#include "ToolChains/Contiki.h"
19#include "ToolChains/CrossWindows.h"
20#include "ToolChains/Cuda.h"
21#include "ToolChains/Darwin.h"
22#include "ToolChains/DragonFly.h"
23#include "ToolChains/FreeBSD.h"
24#include "ToolChains/Fuchsia.h"
25#include "ToolChains/Gnu.h"
Yaxun Liuf6144222018-05-30 00:53:50 +000026#include "ToolChains/HIP.h"
David L. Jonesf561aba2017-03-08 01:02:16 +000027#include "ToolChains/Haiku.h"
28#include "ToolChains/Hexagon.h"
29#include "ToolChains/Lanai.h"
30#include "ToolChains/Linux.h"
Yaxun Liuf6144222018-05-30 00:53:50 +000031#include "ToolChains/MSVC.h"
David L. Jonesf561aba2017-03-08 01:02:16 +000032#include "ToolChains/MinGW.h"
33#include "ToolChains/Minix.h"
Konstantin Zhuravlyove37b32c2017-03-08 22:36:04 +000034#include "ToolChains/MipsLinux.h"
David L. Jonesf561aba2017-03-08 01:02:16 +000035#include "ToolChains/Myriad.h"
36#include "ToolChains/NaCl.h"
37#include "ToolChains/NetBSD.h"
38#include "ToolChains/OpenBSD.h"
39#include "ToolChains/PS4CPU.h"
40#include "ToolChains/Solaris.h"
41#include "ToolChains/TCE.h"
42#include "ToolChains/WebAssembly.h"
43#include "ToolChains/XCore.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000044#include "clang/Basic/Version.h"
Benjamin Kramerd45b2052015-10-07 15:48:01 +000045#include "clang/Basic/VirtualFileSystem.h"
Alp Toker1d257e12014-06-04 03:28:55 +000046#include "clang/Config/config.h"
Daniel Dunbar1688f1a2009-03-12 07:58:46 +000047#include "clang/Driver/Action.h"
Daniel Dunbarb2cd66b2009-03-04 20:49:20 +000048#include "clang/Driver/Compilation.h"
Daniel Dunbarc0b3e952009-03-12 08:55:43 +000049#include "clang/Driver/DriverDiagnostic.h"
Daniel Dunbare75d8342009-03-16 06:56:51 +000050#include "clang/Driver/Job.h"
Daniel Dunbarb2cd66b2009-03-04 20:49:20 +000051#include "clang/Driver/Options.h"
Peter Collingbournea4ccff32015-02-20 20:30:56 +000052#include "clang/Driver/SanitizerArgs.h"
Daniel Dunbare75d8342009-03-16 06:56:51 +000053#include "clang/Driver/Tool.h"
54#include "clang/Driver/ToolChain.h"
Chris Lattnerce6c42f2011-03-23 04:04:01 +000055#include "llvm/ADT/ArrayRef.h"
Hans Wennborg6ddc6902013-07-27 00:23:45 +000056#include "llvm/ADT/STLExtras.h"
Justin Lebar62907612016-07-06 21:21:39 +000057#include "llvm/ADT/SmallSet.h"
Hans Wennborg23d26a32014-06-18 17:21:50 +000058#include "llvm/ADT/StringExtras.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000059#include "llvm/ADT/StringSet.h"
Hans Wennborg70850d82013-07-18 20:29:38 +000060#include "llvm/ADT/StringSwitch.h"
Nico Weberd637c052018-04-30 13:52:15 +000061#include "llvm/Config/llvm-config.h"
Reid Kleckner898229a2013-06-14 17:17:23 +000062#include "llvm/Option/Arg.h"
63#include "llvm/Option/ArgList.h"
Chandler Carruth5553d0d2014-01-07 11:51:46 +000064#include "llvm/Option/OptSpecifier.h"
Reid Kleckner898229a2013-06-14 17:17:23 +000065#include "llvm/Option/OptTable.h"
66#include "llvm/Option/Option.h"
Serge Pavlov208ac652018-01-01 13:27:01 +000067#include "llvm/Support/CommandLine.h"
David Blaikie79000202011-09-23 05:57:42 +000068#include "llvm/Support/ErrorHandling.h"
Michael J. Spencerf28df4c2010-12-17 21:22:22 +000069#include "llvm/Support/FileSystem.h"
Michael J. Spencer8aaf4992010-11-29 18:12:39 +000070#include "llvm/Support/Path.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000071#include "llvm/Support/PrettyStackTrace.h"
Hans Wennborg23d26a32014-06-18 17:21:50 +000072#include "llvm/Support/Process.h"
Michael J. Spencer8aaf4992010-11-29 18:12:39 +000073#include "llvm/Support/Program.h"
Yaxun Liuf6144222018-05-30 00:53:50 +000074#include "llvm/Support/StringSaver.h"
Dimitry Andric81c40422017-06-06 21:54:21 +000075#include "llvm/Support/TargetRegistry.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000076#include "llvm/Support/raw_ostream.h"
Dylan Noblesmith4f4e7452012-02-02 00:40:14 +000077#include <map>
Ahmed Charlesdfca6f92014-03-09 11:36:40 +000078#include <memory>
Benjamin Kramercfeacf52016-05-27 14:27:13 +000079#include <utility>
Bruno Cardoso Lopes02681c42016-11-17 21:41:22 +000080#if LLVM_ON_UNIX
81#include <unistd.h> // getpid
82#endif
Dylan Noblesmith86780e92012-02-01 14:25:28 +000083
Daniel Dunbarb2cd66b2009-03-04 20:49:20 +000084using namespace clang::driver;
Chris Lattnerada1c912009-03-26 05:56:24 +000085using namespace clang;
Reid Kleckner898229a2013-06-14 17:17:23 +000086using namespace llvm::opt;
Daniel Dunbarb2cd66b2009-03-04 20:49:20 +000087
Petr Hosekdd38d932018-05-29 22:35:39 +000088Driver::Driver(StringRef ClangExecutable, StringRef TargetTriple,
Benjamin Kramerd45b2052015-10-07 15:48:01 +000089 DiagnosticsEngine &Diags,
90 IntrusiveRefCntPtr<vfs::FileSystem> VFS)
Benjamin Kramercfeacf52016-05-27 14:27:13 +000091 : Opts(createDriverOptTable()), Diags(Diags), VFS(std::move(VFS)),
92 Mode(GCCMode), SaveTemps(SaveTempsNone), BitcodeEmbed(EmbedNone),
93 LTOMode(LTOK_None), ClangExecutable(ClangExecutable),
Alex Lorenz045c5142018-04-07 00:03:27 +000094 SysRoot(DEFAULT_SYSROOT), DriverTitle("clang LLVM compiler"),
95 CCPrintOptionsFilename(nullptr), CCPrintHeadersFilename(nullptr),
96 CCLogDiagnosticsFilename(nullptr), CCCPrintBindings(false),
97 CCPrintOptions(false), CCPrintHeaders(false), CCLogDiagnostics(false),
Petr Hosekdd38d932018-05-29 22:35:39 +000098 CCGenDiagnostics(false), TargetTriple(TargetTriple),
Alex Lorenz045c5142018-04-07 00:03:27 +000099 CCCGenericGCCName(""), Saver(Alloc), CheckInputsExist(true),
100 CCCUsePCH(true), GenReproducer(false),
101 SuppressMissingInputWarning(false) {
Daniel Dunbar3f3e2cd2010-01-20 02:35:16 +0000102
Benjamin Kramerd45b2052015-10-07 15:48:01 +0000103 // Provide a sane fallback if no VFS is specified.
104 if (!this->VFS)
105 this->VFS = vfs::getRealFileSystem();
106
Sumanth Gundapaneni3a1592942015-03-03 20:43:12 +0000107 Name = llvm::sys::path::filename(ClangExecutable);
Douglas Katzmana67e50c2015-06-26 15:47:46 +0000108 Dir = llvm::sys::path::parent_path(ClangExecutable);
Benjamin Kramerf420dda2015-10-13 15:19:32 +0000109 InstalledDir = Dir; // Provide a sensible default installed dir.
Bob Wilsona20a1da2013-03-23 05:17:59 +0000110
Serge Pavlov208ac652018-01-01 13:27:01 +0000111#if defined(CLANG_CONFIG_FILE_SYSTEM_DIR)
112 SystemConfigDir = CLANG_CONFIG_FILE_SYSTEM_DIR;
113#endif
114#if defined(CLANG_CONFIG_FILE_USER_DIR)
115 UserConfigDir = CLANG_CONFIG_FILE_USER_DIR;
116#endif
117
Bob Wilsona20a1da2013-03-23 05:17:59 +0000118 // Compute the path to the resource directory.
119 StringRef ClangResourceDir(CLANG_RESOURCE_DIR);
120 SmallString<128> P(Dir);
Chandler Carruthfd3cc702014-12-29 12:09:08 +0000121 if (ClangResourceDir != "") {
Bob Wilsona20a1da2013-03-23 05:17:59 +0000122 llvm::sys::path::append(P, ClangResourceDir);
Chandler Carruthfd3cc702014-12-29 12:09:08 +0000123 } else {
124 StringRef ClangLibdirSuffix(CLANG_LIBDIR_SUFFIX);
Argyrios Kyrtzidisbcae0472017-02-25 18:14:35 +0000125 P = llvm::sys::path::parent_path(Dir);
126 llvm::sys::path::append(P, Twine("lib") + ClangLibdirSuffix, "clang",
Chandler Carruthfd3cc702014-12-29 12:09:08 +0000127 CLANG_VERSION_STRING);
128 }
Bob Wilsona20a1da2013-03-23 05:17:59 +0000129 ResourceDir = P.str();
Daniel Dunbar544ecd12009-03-02 19:59:07 +0000130}
131
Zachary Turneraff19c32016-08-12 17:47:52 +0000132void Driver::ParseDriverMode(StringRef ProgramName,
133 ArrayRef<const char *> Args) {
Martin Storsjo1fab23d2018-04-25 21:23:59 +0000134 if (ClangNameParts.isEmpty())
135 ClangNameParts = ToolChain::getTargetAndModeFromProgramName(ProgramName);
Serge Pavlov4e769842017-08-29 05:22:26 +0000136 setDriverModeFromOption(ClangNameParts.DriverMode);
Hans Wennborg70850d82013-07-18 20:29:38 +0000137
Douglas Katzman6bbffc42015-06-25 18:51:37 +0000138 for (const char *ArgPtr : Args) {
Erich Keane258f0592018-02-07 00:19:58 +0000139 // Ignore nullptrs, they are the response file's EOL markers.
Douglas Katzman6bbffc42015-06-25 18:51:37 +0000140 if (ArgPtr == nullptr)
Reid Kleckneraf5fd6a2014-08-22 19:29:30 +0000141 continue;
Douglas Katzman6bbffc42015-06-25 18:51:37 +0000142 const StringRef Arg = ArgPtr;
Zachary Turneraff19c32016-08-12 17:47:52 +0000143 setDriverModeFromOption(Arg);
Hans Wennborg70850d82013-07-18 20:29:38 +0000144 }
145}
146
Zachary Turneraff19c32016-08-12 17:47:52 +0000147void Driver::setDriverModeFromOption(StringRef Opt) {
148 const std::string OptName =
149 getOpts().getOption(options::OPT_driver_mode).getPrefixedName();
150 if (!Opt.startswith(OptName))
151 return;
152 StringRef Value = Opt.drop_front(OptName.size());
153
Erich Keane2908a042018-02-12 17:47:01 +0000154 if (auto M = llvm::StringSwitch<llvm::Optional<DriverMode>>(Value)
155 .Case("gcc", GCCMode)
156 .Case("g++", GXXMode)
157 .Case("cpp", CPPMode)
158 .Case("cl", CLMode)
159 .Default(None))
160 Mode = *M;
Zachary Turneraff19c32016-08-12 17:47:52 +0000161 else
162 Diag(diag::err_drv_unsupported_option_argument) << OptName << Value;
163}
164
Benjamin Kramer43c0f482017-06-30 13:21:27 +0000165InputArgList Driver::ParseArgStrings(ArrayRef<const char *> ArgStrings,
166 bool &ContainsError) {
Daniel Dunbar2608c542009-03-18 01:38:48 +0000167 llvm::PrettyStackTraceString CrashInfo("Command line argument parsing");
Benjamin Kramer43c0f482017-06-30 13:21:27 +0000168 ContainsError = false;
Hans Wennborg6ddc6902013-07-27 00:23:45 +0000169
170 unsigned IncludedFlagsBitmask;
171 unsigned ExcludedFlagsBitmask;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +0000172 std::tie(IncludedFlagsBitmask, ExcludedFlagsBitmask) =
Douglas Katzmana67e50c2015-06-26 15:47:46 +0000173 getIncludeExcludeOptionFlagMasks();
Hans Wennborg6ddc6902013-07-27 00:23:45 +0000174
Daniel Dunbar52ed5fe2009-11-19 06:35:06 +0000175 unsigned MissingArgIndex, MissingArgCount;
David Blaikie69a1d8c2015-06-22 22:07:27 +0000176 InputArgList Args =
David Blaikie6d492ad2015-06-21 06:32:36 +0000177 getOpts().ParseArgs(ArgStrings, MissingArgIndex, MissingArgCount,
178 IncludedFlagsBitmask, ExcludedFlagsBitmask);
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +0000179
Daniel Dunbar52ed5fe2009-11-19 06:35:06 +0000180 // Check for missing argument error.
Benjamin Kramer43c0f482017-06-30 13:21:27 +0000181 if (MissingArgCount) {
182 Diag(diag::err_drv_missing_argument)
David Blaikie69a1d8c2015-06-22 22:07:27 +0000183 << Args.getArgString(MissingArgIndex) << MissingArgCount;
Benjamin Kramer43c0f482017-06-30 13:21:27 +0000184 ContainsError |=
185 Diags.getDiagnosticLevel(diag::err_drv_missing_argument,
186 SourceLocation()) > DiagnosticsEngine::Warning;
187 }
Daniel Dunbar65229332009-03-13 11:38:42 +0000188
Daniel Dunbar52ed5fe2009-11-19 06:35:06 +0000189 // Check for unsupported options.
David Blaikie69a1d8c2015-06-22 22:07:27 +0000190 for (const Arg *A : Args) {
Michael J. Spencer66e2b202012-10-19 22:37:06 +0000191 if (A->getOption().hasFlag(options::Unsupported)) {
Brian Gesiak24910762018-01-06 00:25:40 +0000192 unsigned DiagID;
193 auto ArgString = A->getAsString(Args);
194 std::string Nearest;
195 if (getOpts().findNearest(
196 ArgString, Nearest, IncludedFlagsBitmask,
197 ExcludedFlagsBitmask | options::Unsupported) > 1) {
198 DiagID = diag::err_drv_unsupported_opt;
199 Diag(DiagID) << ArgString;
200 } else {
201 DiagID = diag::err_drv_unsupported_opt_with_suggestion;
202 Diag(DiagID) << ArgString << Nearest;
203 }
204 ContainsError |= Diags.getDiagnosticLevel(DiagID, SourceLocation()) >
Benjamin Kramer43c0f482017-06-30 13:21:27 +0000205 DiagnosticsEngine::Warning;
Daniel Dunbard8500f32009-03-22 23:26:43 +0000206 continue;
207 }
Chad Rosierce975d92012-02-22 17:55:22 +0000208
209 // Warn about -mcpu= without an argument.
Douglas Katzmana67e50c2015-06-26 15:47:46 +0000210 if (A->getOption().matches(options::OPT_mcpu_EQ) && A->containsValue("")) {
Benjamin Kramer43c0f482017-06-30 13:21:27 +0000211 Diag(diag::warn_drv_empty_joined_argument) << A->getAsString(Args);
212 ContainsError |= Diags.getDiagnosticLevel(
213 diag::warn_drv_empty_joined_argument,
214 SourceLocation()) > DiagnosticsEngine::Warning;
Chad Rosierce975d92012-02-22 17:55:22 +0000215 }
Daniel Dunbard02cb1d2009-03-05 06:38:47 +0000216 }
217
Benjamin Kramer43c0f482017-06-30 13:21:27 +0000218 for (const Arg *A : Args.filtered(options::OPT_UNKNOWN)) {
Brian Gesiak24910762018-01-06 00:25:40 +0000219 unsigned DiagID;
220 auto ArgString = A->getAsString(Args);
221 std::string Nearest;
222 if (getOpts().findNearest(
223 ArgString, Nearest, IncludedFlagsBitmask, ExcludedFlagsBitmask) > 1) {
224 DiagID = IsCLMode() ? diag::warn_drv_unknown_argument_clang_cl
225 : diag::err_drv_unknown_argument;
226 Diags.Report(DiagID) << ArgString;
227 } else {
228 DiagID = IsCLMode() ? diag::warn_drv_unknown_argument_clang_cl_with_suggestion
229 : diag::err_drv_unknown_argument_with_suggestion;
230 Diags.Report(DiagID) << ArgString << Nearest;
231 }
232 ContainsError |= Diags.getDiagnosticLevel(DiagID, SourceLocation()) >
Benjamin Kramer43c0f482017-06-30 13:21:27 +0000233 DiagnosticsEngine::Warning;
234 }
Rafael Espindola8a2d4962013-09-23 23:55:25 +0000235
Daniel Dunbard02cb1d2009-03-05 06:38:47 +0000236 return Args;
237}
238
Chad Rosier7742b5d2011-07-27 23:36:45 +0000239// Determine which compilation mode we are in. We look for options which
240// affect the phase, starting with the earliest phases, and record which
241// option we used to determine the final phase.
Douglas Katzmana67e50c2015-06-26 15:47:46 +0000242phases::ID Driver::getFinalPhase(const DerivedArgList &DAL,
243 Arg **FinalPhaseArg) const {
Craig Topper92fc2df2014-05-17 16:56:41 +0000244 Arg *PhaseArg = nullptr;
Chad Rosier7742b5d2011-07-27 23:36:45 +0000245 phases::ID FinalPhase;
Eric Christopherf901e852011-08-17 22:59:59 +0000246
Hans Wennborge50cec32014-06-13 20:59:54 +0000247 // -{E,EP,P,M,MM} only run the preprocessor.
Douglas Katzmana67e50c2015-06-26 15:47:46 +0000248 if (CCCIsCPP() || (PhaseArg = DAL.getLastArg(options::OPT_E)) ||
Hans Wennborge50cec32014-06-13 20:59:54 +0000249 (PhaseArg = DAL.getLastArg(options::OPT__SLASH_EP)) ||
Hans Wennborge0053472013-12-20 18:40:46 +0000250 (PhaseArg = DAL.getLastArg(options::OPT_M, options::OPT_MM)) ||
251 (PhaseArg = DAL.getLastArg(options::OPT__SLASH_P))) {
Chad Rosier7742b5d2011-07-27 23:36:45 +0000252 FinalPhase = phases::Preprocess;
Eric Christopherf901e852011-08-17 22:59:59 +0000253
Richard Smithdd4ad3d2016-08-30 19:06:26 +0000254 // --precompile only runs up to precompilation.
255 } else if ((PhaseArg = DAL.getLastArg(options::OPT__precompile))) {
256 FinalPhase = phases::Precompile;
257
Bob Wilson23a55f12014-12-21 07:00:00 +0000258 // -{fsyntax-only,-analyze,emit-ast} only run up to the compiler.
Chad Rosier7742b5d2011-07-27 23:36:45 +0000259 } else if ((PhaseArg = DAL.getLastArg(options::OPT_fsyntax_only)) ||
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +0000260 (PhaseArg = DAL.getLastArg(options::OPT_module_file_info)) ||
Ben Langmuir2cb4a782014-02-05 22:21:15 +0000261 (PhaseArg = DAL.getLastArg(options::OPT_verify_pch)) ||
Chad Rosier7742b5d2011-07-27 23:36:45 +0000262 (PhaseArg = DAL.getLastArg(options::OPT_rewrite_objc)) ||
Fariborz Jahanian73223bb2012-04-02 15:59:19 +0000263 (PhaseArg = DAL.getLastArg(options::OPT_rewrite_legacy_objc)) ||
Ted Kremenekf7639e12012-03-06 20:06:33 +0000264 (PhaseArg = DAL.getLastArg(options::OPT__migrate)) ||
Chad Rosier7742b5d2011-07-27 23:36:45 +0000265 (PhaseArg = DAL.getLastArg(options::OPT__analyze,
Chad Rosier1aeb15a2012-03-06 23:14:35 +0000266 options::OPT__analyze_auto)) ||
Bob Wilson23a55f12014-12-21 07:00:00 +0000267 (PhaseArg = DAL.getLastArg(options::OPT_emit_ast))) {
Chad Rosier7742b5d2011-07-27 23:36:45 +0000268 FinalPhase = phases::Compile;
269
Bob Wilson23a55f12014-12-21 07:00:00 +0000270 // -S only runs up to the backend.
271 } else if ((PhaseArg = DAL.getLastArg(options::OPT_S))) {
272 FinalPhase = phases::Backend;
273
Artem Belevich4242f412015-07-28 21:01:21 +0000274 // -c compilation only runs up to the assembler.
275 } else if ((PhaseArg = DAL.getLastArg(options::OPT_c))) {
Chad Rosier7742b5d2011-07-27 23:36:45 +0000276 FinalPhase = phases::Assemble;
277
278 // Otherwise do everything.
279 } else
280 FinalPhase = phases::Link;
281
282 if (FinalPhaseArg)
283 *FinalPhaseArg = PhaseArg;
284
285 return FinalPhase;
286}
287
David Blaikie0aaa7622017-01-13 17:34:15 +0000288static Arg *MakeInputArg(DerivedArgList &Args, OptTable &Opts,
Martin Storsjo665c7a42018-05-04 06:05:58 +0000289 StringRef Value, bool Claim = true) {
David Blaikie0aaa7622017-01-13 17:34:15 +0000290 Arg *A = new Arg(Opts.getOption(options::OPT_INPUT), Value,
Hans Wennborged1d0722013-08-13 21:32:29 +0000291 Args.getBaseArgs().MakeIndex(Value), Value.data());
Hans Wennborg55362852014-05-02 22:55:30 +0000292 Args.AddSynthesizedArg(A);
Martin Storsjo665c7a42018-05-04 06:05:58 +0000293 if (Claim)
294 A->claim();
Hans Wennborged1d0722013-08-13 21:32:29 +0000295 return A;
296}
297
Daniel Dunbar775d4062010-06-11 22:00:26 +0000298DerivedArgList *Driver::TranslateInputArgs(const InputArgList &Args) const {
299 DerivedArgList *DAL = new DerivedArgList(Args);
300
Daniel Dunbar2cc3f172010-09-17 00:45:02 +0000301 bool HasNostdlib = Args.hasArg(options::OPT_nostdlib);
Nirav Daveb0bb6142015-11-24 16:07:21 +0000302 bool HasNodefaultlib = Args.hasArg(options::OPT_nodefaultlibs);
Saleem Abdulrasool688b6bc2014-12-29 19:01:36 +0000303 for (Arg *A : Args) {
Daniel Dunbarfb3d7472010-06-14 21:23:12 +0000304 // Unfortunately, we have to parse some forwarding options (-Xassembler,
305 // -Xlinker, -Xpreprocessor) because we either integrate their functionality
306 // (assembler and preprocessor), or bypass a previous driver ('collect2').
Daniel Dunbar5a9d1832010-06-14 21:37:09 +0000307
308 // Rewrite linker options, to replace --no-demangle with a custom internal
309 // option.
310 if ((A->getOption().matches(options::OPT_Wl_COMMA) ||
311 A->getOption().matches(options::OPT_Xlinker)) &&
312 A->containsValue("--no-demangle")) {
Daniel Dunbarfb3d7472010-06-14 21:23:12 +0000313 // Add the rewritten no-demangle argument.
314 DAL->AddFlagArg(A, Opts->getOption(options::OPT_Z_Xlinker__no_demangle));
315
316 // Add the remaining values as Xlinker arguments.
Benjamin Kramer72e64312015-09-24 14:48:49 +0000317 for (StringRef Val : A->getValues())
Douglas Katzmana34b7bf2015-06-30 19:32:57 +0000318 if (Val != "--no-demangle")
319 DAL->AddSeparateArg(A, Opts->getOption(options::OPT_Xlinker), Val);
Daniel Dunbarfb3d7472010-06-14 21:23:12 +0000320
321 continue;
322 }
323
Daniel Dunbar5a9d1832010-06-14 21:37:09 +0000324 // Rewrite preprocessor options, to replace -Wp,-MD,FOO which is used by
325 // some build systems. We don't try to be complete here because we don't
326 // care to encourage this usage model.
327 if (A->getOption().matches(options::OPT_Wp_COMMA) &&
Richard Smithbd55daf2012-11-01 04:30:05 +0000328 (A->getValue(0) == StringRef("-MD") ||
329 A->getValue(0) == StringRef("-MMD"))) {
Daniel Dunbar3648ba72010-06-15 20:30:18 +0000330 // Rewrite to -MD/-MMD along with -MF.
Richard Smithbd55daf2012-11-01 04:30:05 +0000331 if (A->getValue(0) == StringRef("-MD"))
Daniel Dunbar3648ba72010-06-15 20:30:18 +0000332 DAL->AddFlagArg(A, Opts->getOption(options::OPT_MD));
333 else
334 DAL->AddFlagArg(A, Opts->getOption(options::OPT_MMD));
Michael J. Spencer70d85be2012-11-07 23:37:14 +0000335 if (A->getNumValues() == 2)
336 DAL->AddSeparateArg(A, Opts->getOption(options::OPT_MF),
337 A->getValue(1));
Daniel Dunbar5a9d1832010-06-14 21:37:09 +0000338 continue;
339 }
340
Shantonu Senafeb03b2010-09-17 18:39:08 +0000341 // Rewrite reserved library names.
342 if (A->getOption().matches(options::OPT_l)) {
Richard Smithbd55daf2012-11-01 04:30:05 +0000343 StringRef Value = A->getValue();
Daniel Dunbar2cc3f172010-09-17 00:45:02 +0000344
Shantonu Senafeb03b2010-09-17 18:39:08 +0000345 // Rewrite unless -nostdlib is present.
Nirav Daveb0bb6142015-11-24 16:07:21 +0000346 if (!HasNostdlib && !HasNodefaultlib && Value == "stdc++") {
Douglas Katzmana67e50c2015-06-26 15:47:46 +0000347 DAL->AddFlagArg(A, Opts->getOption(options::OPT_Z_reserved_lib_stdcxx));
Daniel Dunbar2cc3f172010-09-17 00:45:02 +0000348 continue;
349 }
Shantonu Senafeb03b2010-09-17 18:39:08 +0000350
351 // Rewrite unconditionally.
352 if (Value == "cc_kext") {
Douglas Katzmana67e50c2015-06-26 15:47:46 +0000353 DAL->AddFlagArg(A, Opts->getOption(options::OPT_Z_reserved_lib_cckext));
Shantonu Senafeb03b2010-09-17 18:39:08 +0000354 continue;
355 }
Daniel Dunbar2cc3f172010-09-17 00:45:02 +0000356 }
357
Hans Wennborged1d0722013-08-13 21:32:29 +0000358 // Pick up inputs via the -- option.
359 if (A->getOption().matches(options::OPT__DASH_DASH)) {
360 A->claim();
Benjamin Kramer72e64312015-09-24 14:48:49 +0000361 for (StringRef Val : A->getValues())
Martin Storsjo665c7a42018-05-04 06:05:58 +0000362 DAL->append(MakeInputArg(*DAL, *Opts, Val, false));
Hans Wennborged1d0722013-08-13 21:32:29 +0000363 continue;
364 }
365
Saleem Abdulrasool688b6bc2014-12-29 19:01:36 +0000366 DAL->append(A);
Daniel Dunbarfb3d7472010-06-14 21:23:12 +0000367 }
Daniel Dunbar775d4062010-06-11 22:00:26 +0000368
Andrey Turetskiy6a8b91d2016-04-21 10:16:48 +0000369 // Enforce -static if -miamcu is present.
Andrey Turetskiy5fea71c2016-06-29 10:57:17 +0000370 if (Args.hasFlag(options::OPT_miamcu, options::OPT_mno_iamcu, false))
371 DAL->AddFlagArg(0, Opts->getOption(options::OPT_static));
Andrey Turetskiy6a8b91d2016-04-21 10:16:48 +0000372
Douglas Katzmana67e50c2015-06-26 15:47:46 +0000373// Add a default value of -mlinker-version=, if one was given and the user
374// didn't specify one.
Daniel Dunbar628fcf42010-08-12 00:05:12 +0000375#if defined(HOST_LINK_VERSION)
Tim Northover018578c2015-06-12 19:21:35 +0000376 if (!Args.hasArg(options::OPT_mlinker_version_EQ) &&
377 strlen(HOST_LINK_VERSION) > 0) {
Daniel Dunbar628fcf42010-08-12 00:05:12 +0000378 DAL->AddJoinedArg(0, Opts->getOption(options::OPT_mlinker_version_EQ),
379 HOST_LINK_VERSION);
Daniel Dunbarb613ffc2010-08-17 22:32:45 +0000380 DAL->getLastArg(options::OPT_mlinker_version_EQ)->claim();
Daniel Dunbar628fcf42010-08-12 00:05:12 +0000381 }
382#endif
383
Daniel Dunbar775d4062010-06-11 22:00:26 +0000384 return DAL;
385}
386
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000387/// Compute target triple from args.
Artem Belevich959e0542015-07-10 19:47:55 +0000388///
389/// This routine provides the logic to compute a target triple from various
390/// args passed to the driver and the default triple string.
Andrey Turetskiy6a8b91d2016-04-21 10:16:48 +0000391static llvm::Triple computeTargetTriple(const Driver &D,
Petr Hosekdd38d932018-05-29 22:35:39 +0000392 StringRef TargetTriple,
Artem Belevich959e0542015-07-10 19:47:55 +0000393 const ArgList &Args,
394 StringRef DarwinArchName = "") {
395 // FIXME: Already done in Compilation *Driver::BuildCompilation
396 if (const Arg *A = Args.getLastArg(options::OPT_target))
Petr Hosekdd38d932018-05-29 22:35:39 +0000397 TargetTriple = A->getValue();
Artem Belevich959e0542015-07-10 19:47:55 +0000398
Petr Hosekdd38d932018-05-29 22:35:39 +0000399 llvm::Triple Target(llvm::Triple::normalize(TargetTriple));
Artem Belevich959e0542015-07-10 19:47:55 +0000400
401 // Handle Apple-specific options available here.
402 if (Target.isOSBinFormatMachO()) {
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +0000403 // If an explicit Darwin arch name is given, that trumps all.
Artem Belevich959e0542015-07-10 19:47:55 +0000404 if (!DarwinArchName.empty()) {
405 tools::darwin::setTripleTypeForMachOArchName(Target, DarwinArchName);
406 return Target;
407 }
408
409 // Handle the Darwin '-arch' flag.
410 if (Arg *A = Args.getLastArg(options::OPT_arch)) {
411 StringRef ArchName = A->getValue();
412 tools::darwin::setTripleTypeForMachOArchName(Target, ArchName);
413 }
414 }
415
416 // Handle pseudo-target flags '-mlittle-endian'/'-EL' and
417 // '-mbig-endian'/'-EB'.
418 if (Arg *A = Args.getLastArg(options::OPT_mlittle_endian,
419 options::OPT_mbig_endian)) {
420 if (A->getOption().matches(options::OPT_mlittle_endian)) {
421 llvm::Triple LE = Target.getLittleEndianArchVariant();
422 if (LE.getArch() != llvm::Triple::UnknownArch)
423 Target = std::move(LE);
424 } else {
425 llvm::Triple BE = Target.getBigEndianArchVariant();
426 if (BE.getArch() != llvm::Triple::UnknownArch)
427 Target = std::move(BE);
428 }
429 }
430
431 // Skip further flag support on OSes which don't support '-m32' or '-m64'.
Douglas Katzman15a63ed2015-08-12 18:36:12 +0000432 if (Target.getArch() == llvm::Triple::tce ||
433 Target.getOS() == llvm::Triple::Minix)
Artem Belevich959e0542015-07-10 19:47:55 +0000434 return Target;
435
436 // Handle pseudo-target flags '-m64', '-mx32', '-m32' and '-m16'.
Andrey Turetskiy6a8b91d2016-04-21 10:16:48 +0000437 Arg *A = Args.getLastArg(options::OPT_m64, options::OPT_mx32,
438 options::OPT_m32, options::OPT_m16);
439 if (A) {
Artem Belevich959e0542015-07-10 19:47:55 +0000440 llvm::Triple::ArchType AT = llvm::Triple::UnknownArch;
441
442 if (A->getOption().matches(options::OPT_m64)) {
443 AT = Target.get64BitArchVariant().getArch();
444 if (Target.getEnvironment() == llvm::Triple::GNUX32)
445 Target.setEnvironment(llvm::Triple::GNU);
446 } else if (A->getOption().matches(options::OPT_mx32) &&
447 Target.get64BitArchVariant().getArch() == llvm::Triple::x86_64) {
448 AT = llvm::Triple::x86_64;
449 Target.setEnvironment(llvm::Triple::GNUX32);
450 } else if (A->getOption().matches(options::OPT_m32)) {
451 AT = Target.get32BitArchVariant().getArch();
452 if (Target.getEnvironment() == llvm::Triple::GNUX32)
453 Target.setEnvironment(llvm::Triple::GNU);
454 } else if (A->getOption().matches(options::OPT_m16) &&
455 Target.get32BitArchVariant().getArch() == llvm::Triple::x86) {
456 AT = llvm::Triple::x86;
457 Target.setEnvironment(llvm::Triple::CODE16);
458 }
459
460 if (AT != llvm::Triple::UnknownArch && AT != Target.getArch())
461 Target.setArch(AT);
462 }
463
Andrey Turetskiy6a8b91d2016-04-21 10:16:48 +0000464 // Handle -miamcu flag.
Andrey Turetskiy5fea71c2016-06-29 10:57:17 +0000465 if (Args.hasFlag(options::OPT_miamcu, options::OPT_mno_iamcu, false)) {
466 if (Target.get32BitArchVariant().getArch() != llvm::Triple::x86)
467 D.Diag(diag::err_drv_unsupported_opt_for_target) << "-miamcu"
468 << Target.str();
Andrey Turetskiy6a8b91d2016-04-21 10:16:48 +0000469
Andrey Turetskiy5fea71c2016-06-29 10:57:17 +0000470 if (A && !A->getOption().matches(options::OPT_m32))
471 D.Diag(diag::err_drv_argument_not_allowed_with)
472 << "-miamcu" << A->getBaseArg().getAsString(Args);
Andrey Turetskiy6a8b91d2016-04-21 10:16:48 +0000473
Andrey Turetskiy5fea71c2016-06-29 10:57:17 +0000474 Target.setArch(llvm::Triple::x86);
475 Target.setArchName("i586");
476 Target.setEnvironment(llvm::Triple::UnknownEnvironment);
477 Target.setEnvironmentName("");
478 Target.setOS(llvm::Triple::ELFIAMCU);
479 Target.setVendor(llvm::Triple::UnknownVendor);
480 Target.setVendorName("intel");
Andrey Turetskiy6a8b91d2016-04-21 10:16:48 +0000481 }
482
Artem Belevich959e0542015-07-10 19:47:55 +0000483 return Target;
484}
485
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000486// Parse the LTO options and record the type of LTO compilation
Teresa Johnson945bc502015-10-15 20:35:53 +0000487// based on which -f(no-)?lto(=.*)? option occurs last.
488void Driver::setLTOMode(const llvm::opt::ArgList &Args) {
489 LTOMode = LTOK_None;
490 if (!Args.hasFlag(options::OPT_flto, options::OPT_flto_EQ,
491 options::OPT_fno_lto, false))
492 return;
493
494 StringRef LTOName("full");
495
496 const Arg *A = Args.getLastArg(options::OPT_flto_EQ);
Teresa Johnson6ef80dc2015-11-02 18:03:12 +0000497 if (A)
498 LTOName = A->getValue();
Teresa Johnson945bc502015-10-15 20:35:53 +0000499
500 LTOMode = llvm::StringSwitch<LTOKind>(LTOName)
501 .Case("full", LTOK_Full)
502 .Case("thin", LTOK_Thin)
503 .Default(LTOK_Unknown);
504
505 if (LTOMode == LTOK_Unknown) {
506 assert(A);
507 Diag(diag::err_drv_unsupported_option_argument) << A->getOption().getName()
508 << A->getValue();
509 }
510}
511
Samuel Antao39f9da22016-10-27 16:38:05 +0000512/// Compute the desired OpenMP runtime from the flags provided.
513Driver::OpenMPRuntimeKind Driver::getOpenMPRuntime(const ArgList &Args) const {
514 StringRef RuntimeName(CLANG_DEFAULT_OPENMP_RUNTIME);
515
516 const Arg *A = Args.getLastArg(options::OPT_fopenmp_EQ);
517 if (A)
518 RuntimeName = A->getValue();
519
520 auto RT = llvm::StringSwitch<OpenMPRuntimeKind>(RuntimeName)
521 .Case("libomp", OMPRT_OMP)
522 .Case("libgomp", OMPRT_GOMP)
523 .Case("libiomp5", OMPRT_IOMP5)
524 .Default(OMPRT_Unknown);
525
526 if (RT == OMPRT_Unknown) {
527 if (A)
528 Diag(diag::err_drv_unsupported_option_argument)
529 << A->getOption().getName() << A->getValue();
530 else
531 // FIXME: We could use a nicer diagnostic here.
532 Diag(diag::err_drv_unsupported_opt) << "-fopenmp";
533 }
534
535 return RT;
536}
537
Samuel Antaoc1ffba52016-06-13 18:10:57 +0000538void Driver::CreateOffloadingDeviceToolChains(Compilation &C,
539 InputList &Inputs) {
540
541 //
Yaxun Liuf5a6b962018-05-11 19:21:39 +0000542 // CUDA/HIP
Samuel Antaoc1ffba52016-06-13 18:10:57 +0000543 //
Yaxun Liuf6144222018-05-30 00:53:50 +0000544 // We need to generate a CUDA/HIP toolchain if any of the inputs has a CUDA
Yaxun Liuf5a6b962018-05-11 19:21:39 +0000545 // or HIP type. However, mixed CUDA/HIP compilation is not supported.
546 bool IsCuda =
547 llvm::any_of(Inputs, [](std::pair<types::ID, const llvm::opt::Arg *> &I) {
Samuel Antaoc1ffba52016-06-13 18:10:57 +0000548 return types::isCuda(I.first);
Yaxun Liuf5a6b962018-05-11 19:21:39 +0000549 });
550 bool IsHIP =
551 llvm::any_of(Inputs,
552 [](std::pair<types::ID, const llvm::opt::Arg *> &I) {
553 return types::isHIP(I.first);
554 }) ||
555 C.getInputArgs().hasArg(options::OPT_hip_link);
556 if (IsCuda && IsHIP) {
557 Diag(clang::diag::err_drv_mix_cuda_hip);
558 return;
559 }
Yaxun Liuf6144222018-05-30 00:53:50 +0000560 if (IsCuda) {
Justin Lebar66c4fd72016-11-18 00:41:22 +0000561 const ToolChain *HostTC = C.getSingleOffloadToolChain<Action::OFK_Host>();
562 const llvm::Triple &HostTriple = HostTC->getTriple();
Yaxun Liuf5a6b962018-05-11 19:21:39 +0000563 StringRef DeviceTripleStr;
Yaxun Liuf6144222018-05-30 00:53:50 +0000564 auto OFK = Action::OFK_Cuda;
565 DeviceTripleStr =
566 HostTriple.isArch64Bit() ? "nvptx64-nvidia-cuda" : "nvptx-nvidia-cuda";
Yaxun Liuf5a6b962018-05-11 19:21:39 +0000567 llvm::Triple CudaTriple(DeviceTripleStr);
Yaxun Liuf6144222018-05-30 00:53:50 +0000568 // Use the CUDA and host triples as the key into the ToolChains map,
Yaxun Liuf5a6b962018-05-11 19:21:39 +0000569 // because the device toolchain we create depends on both.
David Blaikie6ad71012017-01-13 18:53:43 +0000570 auto &CudaTC = ToolChains[CudaTriple.str() + "/" + HostTriple.str()];
Justin Lebar66c4fd72016-11-18 00:41:22 +0000571 if (!CudaTC) {
David Blaikie6ad71012017-01-13 18:53:43 +0000572 CudaTC = llvm::make_unique<toolchains::CudaToolChain>(
Yaxun Liuf5a6b962018-05-11 19:21:39 +0000573 *this, CudaTriple, *HostTC, C.getInputArgs(), OFK);
Justin Lebar66c4fd72016-11-18 00:41:22 +0000574 }
Yaxun Liuf5a6b962018-05-11 19:21:39 +0000575 C.addOffloadDeviceToolChain(CudaTC.get(), OFK);
Yaxun Liuf6144222018-05-30 00:53:50 +0000576 } else if (IsHIP) {
577 const ToolChain *HostTC = C.getSingleOffloadToolChain<Action::OFK_Host>();
578 const llvm::Triple &HostTriple = HostTC->getTriple();
579 StringRef DeviceTripleStr;
580 auto OFK = Action::OFK_HIP;
581 DeviceTripleStr = "amdgcn-amd-amdhsa";
582 llvm::Triple HIPTriple(DeviceTripleStr);
583 // Use the HIP and host triples as the key into the ToolChains map,
584 // because the device toolchain we create depends on both.
585 auto &HIPTC = ToolChains[HIPTriple.str() + "/" + HostTriple.str()];
586 if (!HIPTC) {
587 HIPTC = llvm::make_unique<toolchains::HIPToolChain>(
588 *this, HIPTriple, *HostTC, C.getInputArgs());
589 }
590 C.addOffloadDeviceToolChain(HIPTC.get(), OFK);
Samuel Antaoc1ffba52016-06-13 18:10:57 +0000591 }
592
593 //
Samuel Antao39f9da22016-10-27 16:38:05 +0000594 // OpenMP
595 //
596 // We need to generate an OpenMP toolchain if the user specified targets with
597 // the -fopenmp-targets option.
598 if (Arg *OpenMPTargets =
599 C.getInputArgs().getLastArg(options::OPT_fopenmp_targets_EQ)) {
600 if (OpenMPTargets->getNumValues()) {
601 // We expect that -fopenmp-targets is always used in conjunction with the
602 // option -fopenmp specifying a valid runtime with offloading support,
603 // i.e. libomp or libiomp.
604 bool HasValidOpenMPRuntime = C.getInputArgs().hasFlag(
605 options::OPT_fopenmp, options::OPT_fopenmp_EQ,
606 options::OPT_fno_openmp, false);
607 if (HasValidOpenMPRuntime) {
608 OpenMPRuntimeKind OpenMPKind = getOpenMPRuntime(C.getInputArgs());
609 HasValidOpenMPRuntime =
610 OpenMPKind == OMPRT_OMP || OpenMPKind == OMPRT_IOMP5;
611 }
612
613 if (HasValidOpenMPRuntime) {
614 llvm::StringMap<const char *> FoundNormalizedTriples;
615 for (const char *Val : OpenMPTargets->getValues()) {
616 llvm::Triple TT(Val);
617 std::string NormalizedName = TT.normalize();
618
619 // Make sure we don't have a duplicate triple.
620 auto Duplicate = FoundNormalizedTriples.find(NormalizedName);
621 if (Duplicate != FoundNormalizedTriples.end()) {
622 Diag(clang::diag::warn_drv_omp_offload_target_duplicate)
623 << Val << Duplicate->second;
624 continue;
625 }
626
627 // Store the current triple so that we can check for duplicates in the
628 // following iterations.
629 FoundNormalizedTriples[NormalizedName] = Val;
630
631 // If the specified target is invalid, emit a diagnostic.
632 if (TT.getArch() == llvm::Triple::UnknownArch)
633 Diag(clang::diag::err_drv_invalid_omp_target) << Val;
634 else {
Gheorghe-Teodor Bercea6a5df722017-07-06 16:08:15 +0000635 const ToolChain *TC;
636 // CUDA toolchains have to be selected differently. They pair host
637 // and device in their implementation.
638 if (TT.isNVPTX()) {
639 const ToolChain *HostTC =
640 C.getSingleOffloadToolChain<Action::OFK_Host>();
641 assert(HostTC && "Host toolchain should be always defined.");
642 auto &CudaTC =
Gheorghe-Teodor Bercea52898432017-08-09 01:02:19 +0000643 ToolChains[TT.str() + "/" + HostTC->getTriple().normalize()];
Gheorghe-Teodor Bercea6a5df722017-07-06 16:08:15 +0000644 if (!CudaTC)
645 CudaTC = llvm::make_unique<toolchains::CudaToolChain>(
Gheorghe-Teodor Bercea2c926932017-08-08 14:33:05 +0000646 *this, TT, *HostTC, C.getInputArgs(), Action::OFK_OpenMP);
Gheorghe-Teodor Bercea6a5df722017-07-06 16:08:15 +0000647 TC = CudaTC.get();
648 } else
649 TC = &getToolChain(C.getInputArgs(), TT);
650 C.addOffloadDeviceToolChain(TC, Action::OFK_OpenMP);
Samuel Antao39f9da22016-10-27 16:38:05 +0000651 }
652 }
653 } else
654 Diag(clang::diag::err_drv_expecting_fopenmp_with_fopenmp_targets);
655 } else
656 Diag(clang::diag::warn_drv_empty_joined_argument)
657 << OpenMPTargets->getAsString(C.getInputArgs());
658 }
659
660 //
Samuel Antaoc1ffba52016-06-13 18:10:57 +0000661 // TODO: Add support for other offloading programming models here.
662 //
Samuel Antaoc1ffba52016-06-13 18:10:57 +0000663}
664
Serge Pavlov208ac652018-01-01 13:27:01 +0000665/// Looks the given directories for the specified file.
666///
667/// \param[out] FilePath File path, if the file was found.
668/// \param[in] Dirs Directories used for the search.
669/// \param[in] FileName Name of the file to search for.
670/// \return True if file was found.
671///
672/// Looks for file specified by FileName sequentially in directories specified
673/// by Dirs.
674///
675static bool searchForFile(SmallVectorImpl<char> &FilePath,
676 ArrayRef<std::string> Dirs,
677 StringRef FileName) {
678 SmallString<128> WPath;
679 for (const StringRef &Dir : Dirs) {
680 if (Dir.empty())
681 continue;
682 WPath.clear();
683 llvm::sys::path::append(WPath, Dir, FileName);
684 llvm::sys::path::native(WPath);
685 if (llvm::sys::fs::is_regular_file(WPath)) {
686 FilePath = std::move(WPath);
687 return true;
688 }
689 }
690 return false;
691}
692
693bool Driver::readConfigFile(StringRef FileName) {
694 // Try reading the given file.
695 SmallVector<const char *, 32> NewCfgArgs;
696 if (!llvm::cl::readConfigFile(FileName, Saver, NewCfgArgs)) {
697 Diag(diag::err_drv_cannot_read_config_file) << FileName;
698 return true;
699 }
700
701 // Read options from config file.
702 llvm::SmallString<128> CfgFileName(FileName);
703 llvm::sys::path::native(CfgFileName);
704 ConfigFile = CfgFileName.str();
705 bool ContainErrors;
706 CfgOptions = llvm::make_unique<InputArgList>(
707 ParseArgStrings(NewCfgArgs, ContainErrors));
708 if (ContainErrors) {
709 CfgOptions.reset();
710 return true;
711 }
712
713 if (CfgOptions->hasArg(options::OPT_config)) {
714 CfgOptions.reset();
715 Diag(diag::err_drv_nested_config_file);
716 return true;
717 }
718
719 // Claim all arguments that come from a configuration file so that the driver
720 // does not warn on any that is unused.
721 for (Arg *A : *CfgOptions)
722 A->claim();
723 return false;
724}
725
726bool Driver::loadConfigFile() {
727 std::string CfgFileName;
728 bool FileSpecifiedExplicitly = false;
729
730 // Process options that change search path for config files.
731 if (CLOptions) {
732 if (CLOptions->hasArg(options::OPT_config_system_dir_EQ)) {
733 SmallString<128> CfgDir;
734 CfgDir.append(
735 CLOptions->getLastArgValue(options::OPT_config_system_dir_EQ));
736 if (!CfgDir.empty()) {
Sam McCall296d8322018-01-02 09:35:10 +0000737 if (llvm::sys::fs::make_absolute(CfgDir).value() != 0)
Serge Pavlov208ac652018-01-01 13:27:01 +0000738 SystemConfigDir.clear();
739 else
740 SystemConfigDir = std::string(CfgDir.begin(), CfgDir.end());
741 }
742 }
743 if (CLOptions->hasArg(options::OPT_config_user_dir_EQ)) {
744 SmallString<128> CfgDir;
745 CfgDir.append(
746 CLOptions->getLastArgValue(options::OPT_config_user_dir_EQ));
747 if (!CfgDir.empty()) {
Sam McCall296d8322018-01-02 09:35:10 +0000748 if (llvm::sys::fs::make_absolute(CfgDir).value() != 0)
Serge Pavlov208ac652018-01-01 13:27:01 +0000749 UserConfigDir.clear();
750 else
751 UserConfigDir = std::string(CfgDir.begin(), CfgDir.end());
752 }
753 }
754 }
755
756 // First try to find config file specified in command line.
757 if (CLOptions) {
758 std::vector<std::string> ConfigFiles =
759 CLOptions->getAllArgValues(options::OPT_config);
760 if (ConfigFiles.size() > 1) {
761 Diag(diag::err_drv_duplicate_config);
762 return true;
763 }
764
765 if (!ConfigFiles.empty()) {
766 CfgFileName = ConfigFiles.front();
767 assert(!CfgFileName.empty());
768
769 // If argument contains directory separator, treat it as a path to
770 // configuration file.
771 if (llvm::sys::path::has_parent_path(CfgFileName)) {
772 SmallString<128> CfgFilePath;
773 if (llvm::sys::path::is_relative(CfgFileName))
774 llvm::sys::fs::current_path(CfgFilePath);
775 llvm::sys::path::append(CfgFilePath, CfgFileName);
776 if (!llvm::sys::fs::is_regular_file(CfgFilePath)) {
777 Diag(diag::err_drv_config_file_not_exist) << CfgFilePath;
778 return true;
779 }
780 return readConfigFile(CfgFilePath);
781 }
782
783 FileSpecifiedExplicitly = true;
784 }
785 }
786
787 // If config file is not specified explicitly, try to deduce configuration
788 // from executable name. For instance, an executable 'armv7l-clang' will
789 // search for config file 'armv7l-clang.cfg'.
790 if (CfgFileName.empty() && !ClangNameParts.TargetPrefix.empty())
791 CfgFileName = ClangNameParts.TargetPrefix + '-' + ClangNameParts.ModeSuffix;
792
793 if (CfgFileName.empty())
794 return false;
795
796 // Determine architecture part of the file name, if it is present.
797 StringRef CfgFileArch = CfgFileName;
798 size_t ArchPrefixLen = CfgFileArch.find('-');
799 if (ArchPrefixLen == StringRef::npos)
800 ArchPrefixLen = CfgFileArch.size();
801 llvm::Triple CfgTriple;
802 CfgFileArch = CfgFileArch.take_front(ArchPrefixLen);
803 CfgTriple = llvm::Triple(llvm::Triple::normalize(CfgFileArch));
804 if (CfgTriple.getArch() == llvm::Triple::ArchType::UnknownArch)
805 ArchPrefixLen = 0;
806
807 if (!StringRef(CfgFileName).endswith(".cfg"))
808 CfgFileName += ".cfg";
809
810 // If config file starts with architecture name and command line options
811 // redefine architecture (with options like -m32 -LE etc), try finding new
812 // config file with that architecture.
813 SmallString<128> FixedConfigFile;
814 size_t FixedArchPrefixLen = 0;
815 if (ArchPrefixLen) {
816 // Get architecture name from config file name like 'i386.cfg' or
817 // 'armv7l-clang.cfg'.
818 // Check if command line options changes effective triple.
819 llvm::Triple EffectiveTriple = computeTargetTriple(*this,
820 CfgTriple.getTriple(), *CLOptions);
821 if (CfgTriple.getArch() != EffectiveTriple.getArch()) {
822 FixedConfigFile = EffectiveTriple.getArchName();
823 FixedArchPrefixLen = FixedConfigFile.size();
824 // Append the rest of original file name so that file name transforms
825 // like: i386-clang.cfg -> x86_64-clang.cfg.
826 if (ArchPrefixLen < CfgFileName.size())
827 FixedConfigFile += CfgFileName.substr(ArchPrefixLen);
828 }
829 }
830
831 // Prepare list of directories where config file is searched for.
832 SmallVector<std::string, 3> CfgFileSearchDirs;
833 CfgFileSearchDirs.push_back(UserConfigDir);
834 CfgFileSearchDirs.push_back(SystemConfigDir);
835 CfgFileSearchDirs.push_back(Dir);
836
837 // Try to find config file. First try file with corrected architecture.
838 llvm::SmallString<128> CfgFilePath;
839 if (!FixedConfigFile.empty()) {
840 if (searchForFile(CfgFilePath, CfgFileSearchDirs, FixedConfigFile))
841 return readConfigFile(CfgFilePath);
842 // If 'x86_64-clang.cfg' was not found, try 'x86_64.cfg'.
843 FixedConfigFile.resize(FixedArchPrefixLen);
844 FixedConfigFile.append(".cfg");
845 if (searchForFile(CfgFilePath, CfgFileSearchDirs, FixedConfigFile))
846 return readConfigFile(CfgFilePath);
847 }
848
849 // Then try original file name.
850 if (searchForFile(CfgFilePath, CfgFileSearchDirs, CfgFileName))
851 return readConfigFile(CfgFilePath);
852
853 // Finally try removing driver mode part: 'x86_64-clang.cfg' -> 'x86_64.cfg'.
854 if (!ClangNameParts.ModeSuffix.empty() &&
855 !ClangNameParts.TargetPrefix.empty()) {
856 CfgFileName.assign(ClangNameParts.TargetPrefix);
857 CfgFileName.append(".cfg");
858 if (searchForFile(CfgFilePath, CfgFileSearchDirs, CfgFileName))
859 return readConfigFile(CfgFilePath);
860 }
861
862 // Report error but only if config file was specified explicitly, by option
863 // --config. If it was deduced from executable name, it is not an error.
864 if (FileSpecifiedExplicitly) {
865 Diag(diag::err_drv_config_file_not_found) << CfgFileName;
866 for (const std::string &SearchDir : CfgFileSearchDirs)
867 if (!SearchDir.empty())
868 Diag(diag::note_drv_config_file_searched_in) << SearchDir;
869 return true;
870 }
871
872 return false;
873}
874
Chris Lattner54b16772011-07-23 17:14:25 +0000875Compilation *Driver::BuildCompilation(ArrayRef<const char *> ArgList) {
Daniel Dunbar2608c542009-03-18 01:38:48 +0000876 llvm::PrettyStackTraceString CrashInfo("Compilation construction");
877
Eric Christopherf901e852011-08-17 22:59:59 +0000878 // FIXME: Handle environment options which affect driver behavior, somewhere
Bill Wendlingadbeb9f2012-03-12 21:24:57 +0000879 // (client?). GCC_EXEC_PREFIX, LPATH, CC_PRINT_OPTIONS.
Chad Rosier82301162011-09-14 00:47:55 +0000880
David Majnemer85c25b42016-07-24 17:44:03 +0000881 if (Optional<std::string> CompilerPathValue =
882 llvm::sys::Process::GetEnv("COMPILER_PATH")) {
883 StringRef CompilerPath = *CompilerPathValue;
Chad Rosier82301162011-09-14 00:47:55 +0000884 while (!CompilerPath.empty()) {
Douglas Katzmana67e50c2015-06-26 15:47:46 +0000885 std::pair<StringRef, StringRef> Split =
886 CompilerPath.split(llvm::sys::EnvPathSeparator);
Chad Rosier82301162011-09-14 00:47:55 +0000887 PrefixDirs.push_back(Split.first);
888 CompilerPath = Split.second;
889 }
890 }
Daniel Dunbar5e0f6af2009-03-13 00:51:18 +0000891
Hans Wennborg70850d82013-07-18 20:29:38 +0000892 // We look for the driver mode option early, because the mode can affect
893 // how other options are parsed.
Zachary Turneraff19c32016-08-12 17:47:52 +0000894 ParseDriverMode(ClangExecutable, ArgList.slice(1));
Hans Wennborg70850d82013-07-18 20:29:38 +0000895
Daniel Dunbar5e0f6af2009-03-13 00:51:18 +0000896 // FIXME: What are we going to do with -V and -b?
897
Serge Pavlov208ac652018-01-01 13:27:01 +0000898 // Arguments specified in command line.
899 bool ContainsError;
900 CLOptions = llvm::make_unique<InputArgList>(
901 ParseArgStrings(ArgList.slice(1), ContainsError));
902
903 // Try parsing configuration file.
904 if (!ContainsError)
905 ContainsError = loadConfigFile();
906 bool HasConfigFile = !ContainsError && (CfgOptions.get() != nullptr);
907
908 // All arguments, from both config file and command line.
909 InputArgList Args = std::move(HasConfigFile ? std::move(*CfgOptions)
910 : std::move(*CLOptions));
911 if (HasConfigFile)
912 for (auto *Opt : *CLOptions) {
Serge Pavlovf015a562018-04-26 06:28:47 +0000913 if (Opt->getOption().matches(options::OPT_config))
914 continue;
915 unsigned Index = Args.MakeIndex(Opt->getSpelling());
Serge Pavlov208ac652018-01-01 13:27:01 +0000916 const Arg *BaseArg = &Opt->getBaseArg();
917 if (BaseArg == Opt)
918 BaseArg = nullptr;
919 Arg *Copy = new llvm::opt::Arg(Opt->getOption(), Opt->getSpelling(),
Serge Pavlovf015a562018-04-26 06:28:47 +0000920 Index, BaseArg);
Serge Pavlov208ac652018-01-01 13:27:01 +0000921 Copy->getValues() = Opt->getValues();
922 if (Opt->isClaimed())
923 Copy->claim();
924 Args.append(Copy);
925 }
926
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +0000927 // FIXME: This stuff needs to go into the Compilation, not the driver.
Douglas Katzmanb7e8ef02015-06-25 19:37:41 +0000928 bool CCCPrintPhases;
Daniel Dunbard02cb1d2009-03-05 06:38:47 +0000929
Filipe Cabecinhas136f35e2015-07-18 06:35:24 +0000930 // Silence driver warnings if requested
931 Diags.setIgnoreAllWarnings(Args.hasArg(options::OPT_w));
932
Rafael Espindola59ae7992009-12-07 18:28:29 +0000933 // -no-canonical-prefixes is used very early in main.
David Blaikie69a1d8c2015-06-22 22:07:27 +0000934 Args.ClaimAllArgs(options::OPT_no_canonical_prefixes);
Rafael Espindola59ae7992009-12-07 18:28:29 +0000935
Daniel Dunbar926f81f2010-08-02 02:38:03 +0000936 // Ignore -pipe.
David Blaikie69a1d8c2015-06-22 22:07:27 +0000937 Args.ClaimAllArgs(options::OPT_pipe);
Daniel Dunbar926f81f2010-08-02 02:38:03 +0000938
Daniel Dunbaracd69572009-12-04 21:55:23 +0000939 // Extract -ccc args.
Daniel Dunbaree66cf22009-03-10 20:52:46 +0000940 //
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +0000941 // FIXME: We need to figure out where this behavior should live. Most of it
942 // should be outside in the client; the parts that aren't should have proper
943 // options, either by introducing new ones or by overloading gcc ones like -V
944 // or -b.
Douglas Katzmanb7e8ef02015-06-25 19:37:41 +0000945 CCCPrintPhases = Args.hasArg(options::OPT_ccc_print_phases);
David Blaikie69a1d8c2015-06-22 22:07:27 +0000946 CCCPrintBindings = Args.hasArg(options::OPT_ccc_print_bindings);
947 if (const Arg *A = Args.getLastArg(options::OPT_ccc_gcc_name))
Richard Smithbd55daf2012-11-01 04:30:05 +0000948 CCCGenericGCCName = A->getValue();
David Blaikie69a1d8c2015-06-22 22:07:27 +0000949 CCCUsePCH =
950 Args.hasFlag(options::OPT_ccc_pch_is_pch, options::OPT_ccc_pch_is_pth);
Bruno Cardoso Lopes52dfe712017-04-12 21:46:20 +0000951 GenReproducer = Args.hasFlag(options::OPT_gen_reproducer,
952 options::OPT_fno_crash_diagnostics,
953 !!::getenv("FORCE_CLANG_DIAGNOSTICS_CRASH"));
Petr Hosekdd38d932018-05-29 22:35:39 +0000954 // FIXME: TargetTriple is used by the target-prefixed calls to as/ld
Joerg Sonnenberger17d75512012-02-22 19:15:16 +0000955 // and getToolChain is const.
Hans Wennborg2e274592013-08-13 23:38:57 +0000956 if (IsCLMode()) {
Hans Wennborg73609a02014-03-28 01:19:04 +0000957 // clang-cl targets MSVC-style Win32.
Petr Hosekdd38d932018-05-29 22:35:39 +0000958 llvm::Triple T(TargetTriple);
Hans Wennborg9d9ce7a2014-03-28 20:49:28 +0000959 T.setOS(llvm::Triple::Win32);
Hans Wennborg0f0e8d62015-09-18 17:11:50 +0000960 T.setVendor(llvm::Triple::PC);
Hans Wennborg9d9ce7a2014-03-28 20:49:28 +0000961 T.setEnvironment(llvm::Triple::MSVC);
Oleg Ranevskyy80523182017-08-31 20:31:30 +0000962 T.setObjectFormat(llvm::Triple::COFF);
Petr Hosekdd38d932018-05-29 22:35:39 +0000963 TargetTriple = T.str();
Hans Wennborg2e274592013-08-13 23:38:57 +0000964 }
David Blaikie69a1d8c2015-06-22 22:07:27 +0000965 if (const Arg *A = Args.getLastArg(options::OPT_target))
Petr Hosekdd38d932018-05-29 22:35:39 +0000966 TargetTriple = A->getValue();
David Blaikie69a1d8c2015-06-22 22:07:27 +0000967 if (const Arg *A = Args.getLastArg(options::OPT_ccc_install_dir))
Richard Smithbd55daf2012-11-01 04:30:05 +0000968 Dir = InstalledDir = A->getValue();
David Blaikie69a1d8c2015-06-22 22:07:27 +0000969 for (const Arg *A : Args.filtered(options::OPT_B)) {
Benjamin Kramer1a648d12011-02-08 20:31:42 +0000970 A->claim();
Richard Smithbd55daf2012-11-01 04:30:05 +0000971 PrefixDirs.push_back(A->getValue(0));
Benjamin Kramer1a648d12011-02-08 20:31:42 +0000972 }
David Blaikie69a1d8c2015-06-22 22:07:27 +0000973 if (const Arg *A = Args.getLastArg(options::OPT__sysroot_EQ))
Richard Smithbd55daf2012-11-01 04:30:05 +0000974 SysRoot = A->getValue();
David Blaikie69a1d8c2015-06-22 22:07:27 +0000975 if (const Arg *A = Args.getLastArg(options::OPT__dyld_prefix_EQ))
Peter Collingbourne9d9e1fc2013-05-27 21:40:20 +0000976 DyldPrefix = A->getValue();
Daniel Dunbaree66cf22009-03-10 20:52:46 +0000977
David Blaikie69a1d8c2015-06-22 22:07:27 +0000978 if (const Arg *A = Args.getLastArg(options::OPT_resource_dir))
Bob Wilsona20a1da2013-03-23 05:17:59 +0000979 ResourceDir = A->getValue();
Jim Grosbach061dabf2013-03-12 20:17:58 +0000980
David Blaikie69a1d8c2015-06-22 22:07:27 +0000981 if (const Arg *A = Args.getLastArg(options::OPT_save_temps_EQ)) {
Reid Kleckner68eb60b2015-02-02 22:41:48 +0000982 SaveTemps = llvm::StringSwitch<SaveTempsMode>(A->getValue())
983 .Case("cwd", SaveTempsCwd)
984 .Case("obj", SaveTempsObj)
985 .Default(SaveTempsCwd);
986 }
987
Steven Wu1257cd82016-05-18 17:04:52 +0000988 setLTOMode(Args);
989
Steven Wu844ab6a2016-11-16 06:06:44 +0000990 // Process -fembed-bitcode= flags.
991 if (Arg *A = Args.getLastArg(options::OPT_fembed_bitcode_EQ)) {
992 StringRef Name = A->getValue();
993 unsigned Model = llvm::StringSwitch<unsigned>(Name)
994 .Case("off", EmbedNone)
995 .Case("all", EmbedBitcode)
996 .Case("bitcode", EmbedBitcode)
997 .Case("marker", EmbedMarker)
998 .Default(~0U);
999 if (Model == ~0U) {
1000 Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args)
1001 << Name;
1002 } else
1003 BitcodeEmbed = static_cast<BitcodeEmbedMode>(Model);
Steven Wu574b0f22016-03-01 01:07:58 +00001004 }
1005
David Blaikie69a1d8c2015-06-22 22:07:27 +00001006 std::unique_ptr<llvm::opt::InputArgList> UArgs =
1007 llvm::make_unique<InputArgList>(std::move(Args));
1008
Daniel Dunbar775d4062010-06-11 22:00:26 +00001009 // Perform the default argument translations.
David Blaikie69a1d8c2015-06-22 22:07:27 +00001010 DerivedArgList *TranslatedArgs = TranslateInputArgs(*UArgs);
Daniel Dunbar775d4062010-06-11 22:00:26 +00001011
Chandler Carruthcb916192012-01-25 08:49:21 +00001012 // Owned by the host.
Andrey Turetskiy6a8b91d2016-04-21 10:16:48 +00001013 const ToolChain &TC = getToolChain(
Petr Hosekdd38d932018-05-29 22:35:39 +00001014 *UArgs, computeTargetTriple(*this, TargetTriple, *UArgs));
Chandler Carruthcb916192012-01-25 08:49:21 +00001015
Daniel Dunbar3ce436d2009-03-16 06:42:30 +00001016 // The compilation takes ownership of Args.
Benjamin Kramer43c0f482017-06-30 13:21:27 +00001017 Compilation *C = new Compilation(*this, TC, UArgs.release(), TranslatedArgs,
1018 ContainsError);
Daniel Dunbarf0eddb82009-03-18 02:55:38 +00001019
Daniel Dunbarf0eddb82009-03-18 02:55:38 +00001020 if (!HandleImmediateArgs(*C))
1021 return C;
1022
Chad Rosierecdede82011-08-12 22:08:57 +00001023 // Construct the list of inputs.
1024 InputList Inputs;
Hans Wennborged1d0722013-08-13 21:32:29 +00001025 BuildInputs(C->getDefaultToolChain(), *TranslatedArgs, Inputs);
Chad Rosierecdede82011-08-12 22:08:57 +00001026
Samuel Antaoc1ffba52016-06-13 18:10:57 +00001027 // Populate the tool chains for the offloading devices, if any.
1028 CreateOffloadingDeviceToolChains(*C, Inputs);
Justin Lebar0e450a52016-03-30 23:30:25 +00001029
Chandler Carruth7f1417f2012-01-24 10:43:44 +00001030 // Construct the list of abstract actions to perform for this compilation. On
Tim Northover157d9112014-01-16 08:48:16 +00001031 // MachO targets this uses the driver-driver and universal actions.
1032 if (TC.getTriple().isOSBinFormatMachO())
Artem Belevich5e2a3ec2015-11-17 22:28:40 +00001033 BuildUniversalActions(*C, C->getDefaultToolChain(), Inputs);
Daniel Dunbarf0eddb82009-03-18 02:55:38 +00001034 else
Justin Lebar0f3474c2016-02-11 02:00:50 +00001035 BuildActions(*C, C->getArgs(), Inputs, C->getActions());
Daniel Dunbarf0eddb82009-03-18 02:55:38 +00001036
Douglas Katzmanb7e8ef02015-06-25 19:37:41 +00001037 if (CCCPrintPhases) {
Daniel Dunbareb843be2009-03-18 03:13:20 +00001038 PrintActions(*C);
Daniel Dunbarf0eddb82009-03-18 02:55:38 +00001039 return C;
1040 }
1041
1042 BuildJobs(*C);
Daniel Dunbaradc91e62009-03-15 01:38:15 +00001043
1044 return C;
Daniel Dunbaree66cf22009-03-10 20:52:46 +00001045}
1046
Justin Bognered9cbe02015-07-09 06:58:31 +00001047static void printArgList(raw_ostream &OS, const llvm::opt::ArgList &Args) {
1048 llvm::opt::ArgStringList ASL;
1049 for (const auto *A : Args)
1050 A->render(Args, ASL);
1051
1052 for (auto I = ASL.begin(), E = ASL.end(); I != E; ++I) {
1053 if (I != ASL.begin())
1054 OS << ' ';
1055 Command::printArg(OS, *I, true);
1056 }
1057 OS << '\n';
1058}
1059
Bruno Cardoso Lopes02681c42016-11-17 21:41:22 +00001060bool Driver::getCrashDiagnosticFile(StringRef ReproCrashFilename,
1061 SmallString<128> &CrashDiagDir) {
1062 using namespace llvm::sys;
1063 assert(llvm::Triple(llvm::sys::getProcessTriple()).isOSDarwin() &&
1064 "Only knows about .crash files on Darwin");
1065
1066 // The .crash file can be found on at ~/Library/Logs/DiagnosticReports/
1067 // (or /Library/Logs/DiagnosticReports for root) and has the filename pattern
1068 // clang-<VERSION>_<YYYY-MM-DD-HHMMSS>_<hostname>.crash.
1069 path::home_directory(CrashDiagDir);
1070 if (CrashDiagDir.startswith("/var/root"))
1071 CrashDiagDir = "/";
1072 path::append(CrashDiagDir, "Library/Logs/DiagnosticReports");
1073 int PID =
1074#if LLVM_ON_UNIX
1075 getpid();
1076#else
1077 0;
1078#endif
1079 std::error_code EC;
1080 fs::file_status FileStatus;
1081 TimePoint<> LastAccessTime;
1082 SmallString<128> CrashFilePath;
1083 // Lookup the .crash files and get the one generated by a subprocess spawned
1084 // by this driver invocation.
1085 for (fs::directory_iterator File(CrashDiagDir, EC), FileEnd;
1086 File != FileEnd && !EC; File.increment(EC)) {
1087 StringRef FileName = path::filename(File->path());
1088 if (!FileName.startswith(Name))
1089 continue;
1090 if (fs::status(File->path(), FileStatus))
1091 continue;
1092 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> CrashFile =
1093 llvm::MemoryBuffer::getFile(File->path());
1094 if (!CrashFile)
1095 continue;
1096 // The first line should start with "Process:", otherwise this isn't a real
1097 // .crash file.
1098 StringRef Data = CrashFile.get()->getBuffer();
1099 if (!Data.startswith("Process:"))
1100 continue;
1101 // Parse parent process pid line, e.g: "Parent Process: clang-4.0 [79141]"
1102 size_t ParentProcPos = Data.find("Parent Process:");
1103 if (ParentProcPos == StringRef::npos)
1104 continue;
1105 size_t LineEnd = Data.find_first_of("\n", ParentProcPos);
1106 if (LineEnd == StringRef::npos)
1107 continue;
1108 StringRef ParentProcess = Data.slice(ParentProcPos+15, LineEnd).trim();
1109 int OpenBracket = -1, CloseBracket = -1;
1110 for (size_t i = 0, e = ParentProcess.size(); i < e; ++i) {
1111 if (ParentProcess[i] == '[')
1112 OpenBracket = i;
1113 if (ParentProcess[i] == ']')
1114 CloseBracket = i;
1115 }
1116 // Extract the parent process PID from the .crash file and check whether
1117 // it matches this driver invocation pid.
1118 int CrashPID;
1119 if (OpenBracket < 0 || CloseBracket < 0 ||
1120 ParentProcess.slice(OpenBracket + 1, CloseBracket)
1121 .getAsInteger(10, CrashPID) || CrashPID != PID) {
1122 continue;
1123 }
1124
1125 // Found a .crash file matching the driver pid. To avoid getting an older
1126 // and misleading crash file, continue looking for the most recent.
1127 // FIXME: the driver can dispatch multiple cc1 invocations, leading to
1128 // multiple crashes poiting to the same parent process. Since the driver
1129 // does not collect pid information for the dispatched invocation there's
1130 // currently no way to distinguish among them.
1131 const auto FileAccessTime = FileStatus.getLastModificationTime();
1132 if (FileAccessTime > LastAccessTime) {
1133 CrashFilePath.assign(File->path());
1134 LastAccessTime = FileAccessTime;
1135 }
1136 }
1137
1138 // If found, copy it over to the location of other reproducer files.
1139 if (!CrashFilePath.empty()) {
1140 EC = fs::copy_file(CrashFilePath, ReproCrashFilename);
1141 if (EC)
1142 return false;
1143 return true;
1144 }
1145
1146 return false;
1147}
1148
Eric Christopherf901e852011-08-17 22:59:59 +00001149// When clang crashes, produce diagnostic information including the fully
1150// preprocessed source file(s). Request that the developer attach the
Chad Rosierbe10f982011-08-02 17:58:04 +00001151// diagnostic information to a bug report.
Alex Lorenz045c5142018-04-07 00:03:27 +00001152void Driver::generateCompilationDiagnostics(
1153 Compilation &C, const Command &FailingCommand,
1154 StringRef AdditionalInformation, CompilationDiagnosticReport *Report) {
Chad Rosier877c0a22012-02-22 00:30:39 +00001155 if (C.getArgs().hasArg(options::OPT_fno_crash_diagnostics))
Chad Rosier62135492012-07-09 17:31:28 +00001156 return;
Chad Rosierbee5a1d2012-03-07 00:30:40 +00001157
Chad Rosierdbf46a12013-02-01 18:30:26 +00001158 // Don't try to generate diagnostics for link or dsymutil jobs.
Justin Bognere1a33d12014-10-20 21:02:05 +00001159 if (FailingCommand.getCreator().isLinkJob() ||
1160 FailingCommand.getCreator().isDsymutilJob())
Chad Rosier877c0a22012-02-22 00:30:39 +00001161 return;
1162
Chad Rosier8179f112012-06-19 17:51:34 +00001163 // Print the version of the compiler.
1164 PrintVersion(C, llvm::errs());
1165
Chad Rosierbe10f982011-08-02 17:58:04 +00001166 Diag(clang::diag::note_drv_command_failed_diag_msg)
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001167 << "PLEASE submit a bug report to " BUG_REPORT_URL " and include the "
1168 "crash backtrace, preprocessed source, and associated run script.";
Chad Rosierbe10f982011-08-02 17:58:04 +00001169
1170 // Suppress driver output and emit preprocessor output to temp file.
Hans Wennborg70850d82013-07-18 20:29:38 +00001171 Mode = CPPMode;
Chad Rosierbe10f982011-08-02 17:58:04 +00001172 CCGenDiagnostics = true;
1173
Chad Rosiercdb008d2011-11-02 21:29:05 +00001174 // Save the original job command(s).
Justin Bogner25645152014-10-21 17:24:44 +00001175 Command Cmd = FailingCommand;
Chad Rosiercdb008d2011-11-02 21:29:05 +00001176
Richard Smith5bb4cdf2012-12-20 02:22:15 +00001177 // Keep track of whether we produce any errors while trying to produce
1178 // preprocessed sources.
1179 DiagnosticErrorTrap Trap(Diags);
1180
1181 // Suppress tool output.
Chad Rosierbe10f982011-08-02 17:58:04 +00001182 C.initCompilationForDiagnostics();
Chad Rosierecdede82011-08-12 22:08:57 +00001183
1184 // Construct the list of inputs.
1185 InputList Inputs;
1186 BuildInputs(C.getDefaultToolChain(), C.getArgs(), Inputs);
Chad Rosierbe10f982011-08-02 17:58:04 +00001187
Chad Rosier4f81fc22011-08-12 23:30:05 +00001188 for (InputList::iterator it = Inputs.begin(), ie = Inputs.end(); it != ie;) {
Chad Rosierd57133d2011-08-18 00:22:25 +00001189 bool IgnoreInput = false;
1190
1191 // Ignore input from stdin or any inputs that cannot be preprocessed.
Paul Robinsonf44157d2014-04-28 22:24:44 +00001192 // Check type first as not all linker inputs have a value.
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001193 if (types::getPreprocessedType(it->first) == types::TY_INVALID) {
Paul Robinsonf44157d2014-04-28 22:24:44 +00001194 IgnoreInput = true;
1195 } else if (!strcmp(it->second->getValue(), "-")) {
Chad Rosierd57133d2011-08-18 00:22:25 +00001196 Diag(clang::diag::note_drv_command_failed_diag_msg)
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001197 << "Error generating preprocessed source(s) - "
1198 "ignoring input from stdin.";
Chad Rosierd57133d2011-08-18 00:22:25 +00001199 IgnoreInput = true;
Chad Rosierd57133d2011-08-18 00:22:25 +00001200 }
1201
1202 if (IgnoreInput) {
Chad Rosier4f81fc22011-08-12 23:30:05 +00001203 it = Inputs.erase(it);
1204 ie = Inputs.end();
Chad Rosier6fdf38b2011-08-17 23:08:45 +00001205 } else {
Chad Rosier4f81fc22011-08-12 23:30:05 +00001206 ++it;
Chad Rosier6fdf38b2011-08-17 23:08:45 +00001207 }
Chad Rosier4f81fc22011-08-12 23:30:05 +00001208 }
Chad Rosierd57133d2011-08-18 00:22:25 +00001209
Chad Rosierc5103c32013-01-29 23:57:10 +00001210 if (Inputs.empty()) {
1211 Diag(clang::diag::note_drv_command_failed_diag_msg)
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001212 << "Error generating preprocessed source(s) - "
1213 "no preprocessable inputs.";
Chad Rosierc5103c32013-01-29 23:57:10 +00001214 return;
1215 }
1216
Chad Rosiere75ef402011-09-06 23:52:36 +00001217 // Don't attempt to generate preprocessed files if multiple -arch options are
Chad Rosier636d2832012-02-13 18:16:28 +00001218 // used, unless they're all duplicates.
1219 llvm::StringSet<> ArchNames;
Saleem Abdulrasool688b6bc2014-12-29 19:01:36 +00001220 for (const Arg *A : C.getArgs()) {
Chad Rosiere75ef402011-09-06 23:52:36 +00001221 if (A->getOption().matches(options::OPT_arch)) {
Richard Smithbd55daf2012-11-01 04:30:05 +00001222 StringRef ArchName = A->getValue();
Chad Rosier636d2832012-02-13 18:16:28 +00001223 ArchNames.insert(ArchName);
Chad Rosiere75ef402011-09-06 23:52:36 +00001224 }
1225 }
Chad Rosier636d2832012-02-13 18:16:28 +00001226 if (ArchNames.size() > 1) {
1227 Diag(clang::diag::note_drv_command_failed_diag_msg)
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001228 << "Error generating preprocessed source(s) - cannot generate "
1229 "preprocessed source with multiple -arch options.";
Chad Rosier636d2832012-02-13 18:16:28 +00001230 return;
1231 }
Chad Rosiere75ef402011-09-06 23:52:36 +00001232
Chandler Carruth7f1417f2012-01-24 10:43:44 +00001233 // Construct the list of abstract actions to perform for this compilation. On
1234 // Darwin OSes this uses the driver-driver and builds universal actions.
Chandler Carruthcb916192012-01-25 08:49:21 +00001235 const ToolChain &TC = C.getDefaultToolChain();
Tim Northover157d9112014-01-16 08:48:16 +00001236 if (TC.getTriple().isOSBinFormatMachO())
Artem Belevich5e2a3ec2015-11-17 22:28:40 +00001237 BuildUniversalActions(C, TC, Inputs);
Chad Rosierbe10f982011-08-02 17:58:04 +00001238 else
Justin Lebar0f3474c2016-02-11 02:00:50 +00001239 BuildActions(C, C.getArgs(), Inputs, C.getActions());
Chad Rosierbe10f982011-08-02 17:58:04 +00001240
1241 BuildJobs(C);
1242
1243 // If there were errors building the compilation, quit now.
Richard Smith5bb4cdf2012-12-20 02:22:15 +00001244 if (Trap.hasErrorOccurred()) {
Chad Rosierbe10f982011-08-02 17:58:04 +00001245 Diag(clang::diag::note_drv_command_failed_diag_msg)
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001246 << "Error generating preprocessed source(s).";
Chad Rosierbe10f982011-08-02 17:58:04 +00001247 return;
1248 }
1249
1250 // Generate preprocessed output.
Chad Rosierdd60e092013-01-29 20:15:05 +00001251 SmallVector<std::pair<int, const Command *>, 4> FailingCommands;
Justin Bogner0cd92482015-07-02 22:52:08 +00001252 C.ExecuteJobs(C.getJobs(), FailingCommands);
Chad Rosierbe10f982011-08-02 17:58:04 +00001253
Justin Bognerbc89b182014-10-20 21:20:27 +00001254 // If any of the preprocessing commands failed, clean up and exit.
1255 if (!FailingCommands.empty()) {
Chad Rosierbe10f982011-08-02 17:58:04 +00001256 Diag(clang::diag::note_drv_command_failed_diag_msg)
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001257 << "Error generating preprocessed source(s).";
Justin Bognerbc89b182014-10-20 21:20:27 +00001258 return;
Chad Rosierbe10f982011-08-02 17:58:04 +00001259 }
Justin Bognerbc89b182014-10-20 21:20:27 +00001260
Justin Bognerc1fdf7f2014-10-20 21:47:56 +00001261 const ArgStringList &TempFiles = C.getTempFiles();
1262 if (TempFiles.empty()) {
1263 Diag(clang::diag::note_drv_command_failed_diag_msg)
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001264 << "Error generating preprocessed source(s).";
Justin Bognerc1fdf7f2014-10-20 21:47:56 +00001265 return;
1266 }
1267
Justin Bognerbc89b182014-10-20 21:20:27 +00001268 Diag(clang::diag::note_drv_command_failed_diag_msg)
1269 << "\n********************\n\n"
1270 "PLEASE ATTACH THE FOLLOWING FILES TO THE BUG REPORT:\n"
1271 "Preprocessed source(s) and associated run script(s) are located at:";
Justin Bognerbc89b182014-10-20 21:20:27 +00001272
Justin Bogner659ecc32014-10-20 22:47:23 +00001273 SmallString<128> VFS;
Bruno Cardoso Lopes02681c42016-11-17 21:41:22 +00001274 SmallString<128> ReproCrashFilename;
Justin Bogner659ecc32014-10-20 22:47:23 +00001275 for (const char *TempFile : TempFiles) {
Justin Bognerc1fdf7f2014-10-20 21:47:56 +00001276 Diag(clang::diag::note_drv_command_failed_diag_msg) << TempFile;
Alex Lorenz045c5142018-04-07 00:03:27 +00001277 if (Report)
1278 Report->TemporaryFiles.push_back(TempFile);
Bruno Cardoso Lopes02681c42016-11-17 21:41:22 +00001279 if (ReproCrashFilename.empty()) {
1280 ReproCrashFilename = TempFile;
1281 llvm::sys::path::replace_extension(ReproCrashFilename, ".crash");
1282 }
Justin Bogner659ecc32014-10-20 22:47:23 +00001283 if (StringRef(TempFile).endswith(".cache")) {
1284 // In some cases (modules) we'll dump extra data to help with reproducing
1285 // the crash into a directory next to the output.
1286 VFS = llvm::sys::path::filename(TempFile);
1287 llvm::sys::path::append(VFS, "vfs", "vfs.yaml");
1288 }
1289 }
Justin Bognerc1fdf7f2014-10-20 21:47:56 +00001290
1291 // Assume associated files are based off of the first temporary file.
Justin Bogner25645152014-10-21 17:24:44 +00001292 CrashReportInfo CrashInfo(TempFiles[0], VFS);
Justin Bognerc1fdf7f2014-10-20 21:47:56 +00001293
Bob Haarman7e4d3ff2018-07-09 21:07:20 +00001294 llvm::SmallString<128> Script(CrashInfo.Filename);
1295 llvm::sys::path::replace_extension(Script, "sh");
Justin Bognerc1fdf7f2014-10-20 21:47:56 +00001296 std::error_code EC;
Zachary Turner1f67a3c2018-06-07 19:58:58 +00001297 llvm::raw_fd_ostream ScriptOS(Script, EC, llvm::sys::fs::CD_CreateNew);
Justin Bognerc1fdf7f2014-10-20 21:47:56 +00001298 if (EC) {
1299 Diag(clang::diag::note_drv_command_failed_diag_msg)
Bob Haarman7e4d3ff2018-07-09 21:07:20 +00001300 << "Error generating run script: " << Script << " " << EC.message();
Justin Bognerc1fdf7f2014-10-20 21:47:56 +00001301 } else {
Justin Bogner42220ed2015-03-12 00:14:35 +00001302 ScriptOS << "# Crash reproducer for " << getClangFullVersion() << "\n"
Justin Bognered9cbe02015-07-09 06:58:31 +00001303 << "# Driver args: ";
1304 printArgList(ScriptOS, C.getInputArgs());
1305 ScriptOS << "# Original command: ";
Justin Bogner42220ed2015-03-12 00:14:35 +00001306 Cmd.Print(ScriptOS, "\n", /*Quote=*/true);
Justin Bogner33bdbc62014-10-21 18:03:08 +00001307 Cmd.Print(ScriptOS, "\n", /*Quote=*/true, &CrashInfo);
Alex Lorenz045c5142018-04-07 00:03:27 +00001308 if (!AdditionalInformation.empty())
1309 ScriptOS << "\n# Additional information: " << AdditionalInformation
1310 << "\n";
1311 if (Report)
Bob Haarman7e4d3ff2018-07-09 21:07:20 +00001312 Report->TemporaryFiles.push_back(Script.str());
Justin Bognerc1fdf7f2014-10-20 21:47:56 +00001313 Diag(clang::diag::note_drv_command_failed_diag_msg) << Script;
Justin Bognerbc89b182014-10-20 21:20:27 +00001314 }
Saleem Abdulrasool3661a822015-01-12 02:33:09 +00001315
Bruno Cardoso Lopes02681c42016-11-17 21:41:22 +00001316 // On darwin, provide information about the .crash diagnostic report.
1317 if (llvm::Triple(llvm::sys::getProcessTriple()).isOSDarwin()) {
1318 SmallString<128> CrashDiagDir;
1319 if (getCrashDiagnosticFile(ReproCrashFilename, CrashDiagDir)) {
1320 Diag(clang::diag::note_drv_command_failed_diag_msg)
1321 << ReproCrashFilename.str();
1322 } else { // Suggest a directory for the user to look for .crash files.
1323 llvm::sys::path::append(CrashDiagDir, Name);
1324 CrashDiagDir += "_<YYYY-MM-DD-HHMMSS>_<hostname>.crash";
1325 Diag(clang::diag::note_drv_command_failed_diag_msg)
1326 << "Crash backtrace is located in";
1327 Diag(clang::diag::note_drv_command_failed_diag_msg)
1328 << CrashDiagDir.str();
1329 Diag(clang::diag::note_drv_command_failed_diag_msg)
1330 << "(choose the .crash file that corresponds to your crash)";
1331 }
1332 }
1333
Saleem Abdulrasool3661a822015-01-12 02:33:09 +00001334 for (const auto &A : C.getArgs().filtered(options::OPT_frewrite_map_file,
1335 options::OPT_frewrite_map_file_EQ))
1336 Diag(clang::diag::note_drv_command_failed_diag_msg) << A->getValue();
1337
Justin Bognerbc89b182014-10-20 21:20:27 +00001338 Diag(clang::diag::note_drv_command_failed_diag_msg)
1339 << "\n\n********************";
Chad Rosierbe10f982011-08-02 17:58:04 +00001340}
1341
Justin Bogner0cd92482015-07-02 22:52:08 +00001342void Driver::setUpResponseFiles(Compilation &C, Command &Cmd) {
Oleg Ranevskyycd516372016-01-05 19:54:39 +00001343 // Since commandLineFitsWithinSystemLimits() may underestimate system's capacity
Reid Kleckner0290c9c2014-09-15 17:45:39 +00001344 // if the tool does not support response files, there is a chance/ that things
1345 // will just work without a response file, so we silently just skip it.
Justin Bogner0cd92482015-07-02 22:52:08 +00001346 if (Cmd.getCreator().getResponseFilesSupport() == Tool::RF_None ||
Oleg Ranevskyycd516372016-01-05 19:54:39 +00001347 llvm::sys::commandLineFitsWithinSystemLimits(Cmd.getExecutable(), Cmd.getArguments()))
Reid Kleckner0290c9c2014-09-15 17:45:39 +00001348 return;
1349
1350 std::string TmpName = GetTemporaryPath("response", "txt");
Malcolm Parsonsf76f6502016-11-02 10:39:27 +00001351 Cmd.setResponseFile(C.addTempFile(C.getArgs().MakeArgString(TmpName)));
Reid Kleckner0290c9c2014-09-15 17:45:39 +00001352}
1353
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001354int Driver::ExecuteCompilation(
1355 Compilation &C,
1356 SmallVectorImpl<std::pair<int, const Command *>> &FailingCommands) {
Daniel Dunbar38bfda62009-07-01 20:03:04 +00001357 // Just print if -### was present.
1358 if (C.getArgs().hasArg(options::OPT__HASH_HASH_HASH)) {
Hans Wennborgb212b342013-09-12 18:23:34 +00001359 C.getJobs().Print(llvm::errs(), "\n", true);
Daniel Dunbar38bfda62009-07-01 20:03:04 +00001360 return 0;
1361 }
1362
1363 // If there were errors building the compilation, quit now.
Chad Rosierbe10f982011-08-02 17:58:04 +00001364 if (Diags.hasErrorOccurred())
Daniel Dunbar38bfda62009-07-01 20:03:04 +00001365 return 1;
1366
Reid Kleckner0290c9c2014-09-15 17:45:39 +00001367 // Set up response file names for each command, if necessary
Justin Bogner0cd92482015-07-02 22:52:08 +00001368 for (auto &Job : C.getJobs())
1369 setUpResponseFiles(C, Job);
Reid Kleckner0290c9c2014-09-15 17:45:39 +00001370
Justin Bogner0cd92482015-07-02 22:52:08 +00001371 C.ExecuteJobs(C.getJobs(), FailingCommands);
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001372
Daniel Dunbar07494792010-05-22 00:37:20 +00001373 // If the command succeeded, we are done.
Chad Rosierdd60e092013-01-29 20:15:05 +00001374 if (FailingCommands.empty())
1375 return 0;
Daniel Dunbar07494792010-05-22 00:37:20 +00001376
Chad Rosierdd60e092013-01-29 20:15:05 +00001377 // Otherwise, remove result files and print extra information about abnormal
1378 // failures.
Douglas Katzman6bbffc42015-06-25 18:51:37 +00001379 for (const auto &CmdPair : FailingCommands) {
1380 int Res = CmdPair.first;
1381 const Command *FailingCommand = CmdPair.second;
Daniel Dunbar38bfda62009-07-01 20:03:04 +00001382
Chad Rosierdd60e092013-01-29 20:15:05 +00001383 // Remove result files if we're not saving temps.
Reid Kleckner68eb60b2015-02-02 22:41:48 +00001384 if (!isSaveTempsEnabled()) {
Chad Rosierdd60e092013-01-29 20:15:05 +00001385 const JobAction *JA = cast<JobAction>(&FailingCommand->getSource());
1386 C.CleanupFileMap(C.getResultFiles(), JA, true);
1387
1388 // Failure result files are valid unless we crashed.
1389 if (Res < 0)
1390 C.CleanupFileMap(C.getFailureResultFiles(), JA, true);
1391 }
1392
1393 // Print extra information about abnormal failures, if possible.
1394 //
1395 // This is ad-hoc, but we don't want to be excessively noisy. If the result
Justin Bogner5aaf2e72014-06-26 20:59:36 +00001396 // status was 1, assume the command failed normally. In particular, if it
Chad Rosierdd60e092013-01-29 20:15:05 +00001397 // was the compiler then assume it gave a reasonable error code. Failures
1398 // in other tools are less common, and they generally have worse
1399 // diagnostics, so always print the diagnostic there.
1400 const Tool &FailingTool = FailingCommand->getCreator();
1401
1402 if (!FailingCommand->getCreator().hasGoodDiagnostics() || Res != 1) {
1403 // FIXME: See FIXME above regarding result code interpretation.
1404 if (Res < 0)
1405 Diag(clang::diag::err_drv_command_signalled)
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001406 << FailingTool.getShortName();
Chad Rosierdd60e092013-01-29 20:15:05 +00001407 else
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001408 Diag(clang::diag::err_drv_command_failed) << FailingTool.getShortName()
1409 << Res;
Chad Rosierdd60e092013-01-29 20:15:05 +00001410 }
Peter Collingbourne119cfaa2011-11-21 00:01:05 +00001411 }
Chad Rosierdd60e092013-01-29 20:15:05 +00001412 return 0;
Daniel Dunbar38bfda62009-07-01 20:03:04 +00001413}
1414
Daniel Dunbara7b5e212009-04-15 16:34:29 +00001415void Driver::PrintHelp(bool ShowHidden) const {
Hans Wennborg6ddc6902013-07-27 00:23:45 +00001416 unsigned IncludedFlagsBitmask;
1417 unsigned ExcludedFlagsBitmask;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00001418 std::tie(IncludedFlagsBitmask, ExcludedFlagsBitmask) =
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001419 getIncludeExcludeOptionFlagMasks();
Hans Wennborg6ddc6902013-07-27 00:23:45 +00001420
1421 ExcludedFlagsBitmask |= options::NoDriverOption;
1422 if (!ShowHidden)
1423 ExcludedFlagsBitmask |= HelpHidden;
1424
1425 getOpts().PrintHelp(llvm::outs(), Name.c_str(), DriverTitle.c_str(),
George Rimar5dbfa4e2017-07-26 09:10:17 +00001426 IncludedFlagsBitmask, ExcludedFlagsBitmask,
1427 /*ShowAllAliases=*/false);
Daniel Dunbar7c925282009-03-31 21:38:17 +00001428}
1429
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001430void Driver::PrintVersion(const Compilation &C, raw_ostream &OS) const {
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001431 // FIXME: The following handlers should use a callback mechanism, we don't
1432 // know what the client would like to do.
Ted Kremenek4c0df3d2010-01-23 02:11:34 +00001433 OS << getClangFullVersion() << '\n';
Daniel Dunbarb10248802009-03-26 16:09:13 +00001434 const ToolChain &TC = C.getDefaultToolChain();
Daniel Dunbar08e41d62009-07-21 20:06:58 +00001435 OS << "Target: " << TC.getTripleString() << '\n';
Daniel Dunbar10978e42009-06-16 23:32:58 +00001436
1437 // Print the threading model.
Jonathan Roelofsb140a102014-10-03 21:57:44 +00001438 if (Arg *A = C.getArgs().getLastArg(options::OPT_mthread_model)) {
1439 // Don't print if the ToolChain would have barfed on it already
1440 if (TC.isThreadModelSupported(A->getValue()))
1441 OS << "Thread model: " << A->getValue();
1442 } else
1443 OS << "Thread model: " << TC.getThreadModel();
1444 OS << '\n';
Chandler Carruth9ade6a92015-08-05 17:07:33 +00001445
1446 // Print out the install directory.
1447 OS << "InstalledDir: " << InstalledDir << '\n';
Serge Pavlov208ac652018-01-01 13:27:01 +00001448
1449 // If configuration file was used, print its path.
1450 if (!ConfigFile.empty())
1451 OS << "Configuration file: " << ConfigFile << '\n';
Daniel Dunbar5e0f6af2009-03-13 00:51:18 +00001452}
1453
Chris Lattner86ed5b02010-05-05 05:53:24 +00001454/// PrintDiagnosticCategories - Implement the --print-diagnostic-categories
1455/// option.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001456static void PrintDiagnosticCategories(raw_ostream &OS) {
Argyrios Kyrtzidis0e37afa2011-05-25 05:05:01 +00001457 // Skip the empty category.
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001458 for (unsigned i = 1, max = DiagnosticIDs::getNumberOfCategories(); i != max;
1459 ++i)
Argyrios Kyrtzidis0e37afa2011-05-25 05:05:01 +00001460 OS << i << ',' << DiagnosticIDs::getCategoryNameFromID(i) << '\n';
Chris Lattner86ed5b02010-05-05 05:53:24 +00001461}
1462
Yuka Takahashi41789e42018-03-05 08:54:20 +00001463void Driver::HandleAutocompletions(StringRef PassedFlags) const {
Yuka Takahashi503da8f2018-03-05 09:01:31 +00001464 if (PassedFlags == "")
1465 return;
Yuka Takahashi1a895202017-08-29 17:46:46 +00001466 // Print out all options that start with a given argument. This is used for
1467 // shell autocompletion.
1468 std::vector<std::string> SuggestedCompletions;
Yuka Takahashi41789e42018-03-05 08:54:20 +00001469 std::vector<std::string> Flags;
Yuka Takahashi1a895202017-08-29 17:46:46 +00001470
1471 unsigned short DisableFlags =
1472 options::NoDriverOption | options::Unsupported | options::Ignored;
Yuka Takahashi41789e42018-03-05 08:54:20 +00001473
1474 // Parse PassedFlags by "," as all the command-line flags are passed to this
1475 // function separated by ","
1476 StringRef TargetFlags = PassedFlags;
1477 while (TargetFlags != "") {
1478 StringRef CurFlag;
1479 std::tie(CurFlag, TargetFlags) = TargetFlags.split(",");
1480 Flags.push_back(std::string(CurFlag));
Yuka Takahashi1a895202017-08-29 17:46:46 +00001481 }
1482
Yuka Takahashi41789e42018-03-05 08:54:20 +00001483 // We want to show cc1-only options only when clang is invoked with -cc1 or
1484 // -Xclang.
Yuka Takahashi503da8f2018-03-05 09:01:31 +00001485 if (std::find(Flags.begin(), Flags.end(), "-Xclang") != Flags.end() ||
1486 std::find(Flags.begin(), Flags.end(), "-cc1") != Flags.end())
Yuka Takahashi41789e42018-03-05 08:54:20 +00001487 DisableFlags &= ~options::NoDriverOption;
1488
1489 StringRef Cur;
1490 Cur = Flags.at(Flags.size() - 1);
1491 StringRef Prev;
1492 if (Flags.size() >= 2) {
1493 Prev = Flags.at(Flags.size() - 2);
1494 SuggestedCompletions = Opts->suggestValueCompletions(Prev, Cur);
1495 }
1496
1497 if (SuggestedCompletions.empty())
1498 SuggestedCompletions = Opts->suggestValueCompletions(Cur, "");
1499
1500 if (SuggestedCompletions.empty()) {
Yuka Takahashi1a895202017-08-29 17:46:46 +00001501 // If the flag is in the form of "--autocomplete=-foo",
1502 // we were requested to print out all option names that start with "-foo".
1503 // For example, "--autocomplete=-fsyn" is expanded to "-fsyntax-only".
Yuka Takahashi41789e42018-03-05 08:54:20 +00001504 SuggestedCompletions = Opts->findByPrefix(Cur, DisableFlags);
Yuka Takahashi1a895202017-08-29 17:46:46 +00001505
1506 // We have to query the -W flags manually as they're not in the OptTable.
1507 // TODO: Find a good way to add them to OptTable instead and them remove
1508 // this code.
1509 for (StringRef S : DiagnosticIDs::getDiagnosticFlags())
Yuka Takahashi41789e42018-03-05 08:54:20 +00001510 if (S.startswith(Cur))
Yuka Takahashi1a895202017-08-29 17:46:46 +00001511 SuggestedCompletions.push_back(S);
Yuka Takahashi1a895202017-08-29 17:46:46 +00001512 }
1513
1514 // Sort the autocomplete candidates so that shells print them out in a
1515 // deterministic order. We could sort in any way, but we chose
1516 // case-insensitive sorting for consistency with the -help option
1517 // which prints out options in the case-insensitive alphabetical order.
Mandeep Singh Grangc205d8c2018-03-27 16:50:00 +00001518 llvm::sort(SuggestedCompletions.begin(), SuggestedCompletions.end(),
1519 [](StringRef A, StringRef B) {
1520 if (int X = A.compare_lower(B))
1521 return X < 0;
1522 return A.compare(B) > 0;
Mandeep Singh Grang8f54ae12017-11-20 18:49:14 +00001523 });
Yuka Takahashi1a895202017-08-29 17:46:46 +00001524
1525 llvm::outs() << llvm::join(SuggestedCompletions, "\n") << '\n';
1526}
1527
Daniel Dunbarf0eddb82009-03-18 02:55:38 +00001528bool Driver::HandleImmediateArgs(const Compilation &C) {
Daniel Dunbar18974bd2010-06-11 22:00:19 +00001529 // The order these options are handled in gcc is all over the place, but we
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001530 // don't expect inconsistencies w.r.t. that to matter in practice.
Daniel Dunbar7c925282009-03-31 21:38:17 +00001531
Daniel Dunbar1b09e042010-09-17 02:47:28 +00001532 if (C.getArgs().hasArg(options::OPT_dumpmachine)) {
1533 llvm::outs() << C.getDefaultToolChain().getTripleString() << '\n';
1534 return false;
1535 }
1536
Daniel Dunbara9bbcfa2009-04-04 05:17:38 +00001537 if (C.getArgs().hasArg(options::OPT_dumpversion)) {
Daniel Dunbare26e5002011-01-12 00:43:47 +00001538 // Since -dumpversion is only implemented for pedantic GCC compatibility, we
1539 // return an answer which matches our definition of __VERSION__.
1540 //
1541 // If we want to return a more correct answer some day, then we should
1542 // introduce a non-pedantically GCC compatible mode to Clang in which we
1543 // provide sensible definitions for -dumpversion, __VERSION__, etc.
1544 llvm::outs() << "4.2.1\n";
Daniel Dunbara9bbcfa2009-04-04 05:17:38 +00001545 return false;
1546 }
Daniel Dunbarfb3d7472010-06-14 21:23:12 +00001547
Chris Lattner86ed5b02010-05-05 05:53:24 +00001548 if (C.getArgs().hasArg(options::OPT__print_diagnostic_categories)) {
1549 PrintDiagnosticCategories(llvm::outs());
1550 return false;
1551 }
Daniel Dunbara9bbcfa2009-04-04 05:17:38 +00001552
James Molloya3c85b82012-05-01 14:57:16 +00001553 if (C.getArgs().hasArg(options::OPT_help) ||
Daniel Dunbara7b5e212009-04-15 16:34:29 +00001554 C.getArgs().hasArg(options::OPT__help_hidden)) {
1555 PrintHelp(C.getArgs().hasArg(options::OPT__help_hidden));
Daniel Dunbar7c925282009-03-31 21:38:17 +00001556 return false;
1557 }
1558
Daniel Dunbarb0006ae2009-04-02 15:05:41 +00001559 if (C.getArgs().hasArg(options::OPT__version)) {
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001560 // Follow gcc behavior and use stdout for --version and stderr for -v.
Daniel Dunbar08e41d62009-07-21 20:06:58 +00001561 PrintVersion(C, llvm::outs());
Daniel Dunbarb0006ae2009-04-02 15:05:41 +00001562 return false;
1563 }
1564
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001565 if (C.getArgs().hasArg(options::OPT_v) ||
Daniel Dunbarf0eddb82009-03-18 02:55:38 +00001566 C.getArgs().hasArg(options::OPT__HASH_HASH_HASH)) {
Daniel Dunbar08e41d62009-07-21 20:06:58 +00001567 PrintVersion(C, llvm::errs());
Daniel Dunbar5e0f6af2009-03-13 00:51:18 +00001568 SuppressMissingInputWarning = true;
1569 }
1570
Serge Pavlov208ac652018-01-01 13:27:01 +00001571 if (C.getArgs().hasArg(options::OPT_v)) {
1572 if (!SystemConfigDir.empty())
1573 llvm::errs() << "System configuration file directory: "
1574 << SystemConfigDir << "\n";
1575 if (!UserConfigDir.empty())
1576 llvm::errs() << "User configuration file directory: "
1577 << UserConfigDir << "\n";
1578 }
1579
Daniel Dunbarf0eddb82009-03-18 02:55:38 +00001580 const ToolChain &TC = C.getDefaultToolChain();
Chandler Carruth0ae39aa2013-07-30 17:57:09 +00001581
1582 if (C.getArgs().hasArg(options::OPT_v))
1583 TC.printVerboseInfo(llvm::errs());
1584
Meador Inge51208a32017-04-04 21:46:50 +00001585 if (C.getArgs().hasArg(options::OPT_print_resource_dir)) {
Meador Ingea9113952017-04-05 22:27:20 +00001586 llvm::outs() << ResourceDir << '\n';
Meador Inge51208a32017-04-04 21:46:50 +00001587 return false;
1588 }
1589
Daniel Dunbard972e222009-03-20 04:37:21 +00001590 if (C.getArgs().hasArg(options::OPT_print_search_dirs)) {
1591 llvm::outs() << "programs: =";
Douglas Katzman51fe7bf2015-06-23 22:43:50 +00001592 bool separator = false;
1593 for (const std::string &Path : TC.getProgramPaths()) {
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001594 if (separator)
1595 llvm::outs() << ':';
Douglas Katzman51fe7bf2015-06-23 22:43:50 +00001596 llvm::outs() << Path;
1597 separator = true;
Daniel Dunbard972e222009-03-20 04:37:21 +00001598 }
1599 llvm::outs() << "\n";
Peter Collingbournefa9771f2011-09-06 02:08:31 +00001600 llvm::outs() << "libraries: =" << ResourceDir;
Joerg Sonnenberger9c3e69b2011-07-16 10:50:05 +00001601
Sebastian Pop980920a2012-04-16 04:16:43 +00001602 StringRef sysroot = C.getSysRoot();
Joerg Sonnenberger9c3e69b2011-07-16 10:50:05 +00001603
Douglas Katzman51fe7bf2015-06-23 22:43:50 +00001604 for (const std::string &Path : TC.getFilePaths()) {
1605 // Always print a separator. ResourceDir was the first item shown.
Peter Collingbournefa9771f2011-09-06 02:08:31 +00001606 llvm::outs() << ':';
Douglas Katzman51fe7bf2015-06-23 22:43:50 +00001607 // Interpretation of leading '=' is needed only for NetBSD.
1608 if (Path[0] == '=')
Douglas Katzman26eabf62015-06-24 15:10:30 +00001609 llvm::outs() << sysroot << Path.substr(1);
Joerg Sonnenberger9c3e69b2011-07-16 10:50:05 +00001610 else
Douglas Katzman51fe7bf2015-06-23 22:43:50 +00001611 llvm::outs() << Path;
Daniel Dunbard972e222009-03-20 04:37:21 +00001612 }
1613 llvm::outs() << "\n";
Daniel Dunbar7c925282009-03-31 21:38:17 +00001614 return false;
Daniel Dunbard972e222009-03-20 04:37:21 +00001615 }
1616
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001617 // FIXME: The following handlers should use a callback mechanism, we don't
1618 // know what the client would like to do.
Daniel Dunbarf0eddb82009-03-18 02:55:38 +00001619 if (Arg *A = C.getArgs().getLastArg(options::OPT_print_file_name_EQ)) {
Richard Smithbd55daf2012-11-01 04:30:05 +00001620 llvm::outs() << GetFilePath(A->getValue(), TC) << "\n";
Daniel Dunbar5e0f6af2009-03-13 00:51:18 +00001621 return false;
1622 }
1623
Daniel Dunbarf0eddb82009-03-18 02:55:38 +00001624 if (Arg *A = C.getArgs().getLastArg(options::OPT_print_prog_name_EQ)) {
Saleem Abdulrasoole5f3cf82018-05-01 18:40:42 +00001625 StringRef ProgName = A->getValue();
1626
1627 // Null program name cannot have a path.
1628 if (! ProgName.empty())
1629 llvm::outs() << GetProgramPath(ProgName, TC);
1630
1631 llvm::outs() << "\n";
Daniel Dunbar5e0f6af2009-03-13 00:51:18 +00001632 return false;
1633 }
1634
Yuka Takahashic8068db2017-05-23 18:39:08 +00001635 if (Arg *A = C.getArgs().getLastArg(options::OPT_autocomplete)) {
Yuka Takahashiba5d4af2017-06-20 16:31:31 +00001636 StringRef PassedFlags = A->getValue();
Yuka Takahashi41789e42018-03-05 08:54:20 +00001637 HandleAutocompletions(PassedFlags);
Yuka Takahashic8068db2017-05-23 18:39:08 +00001638 return false;
1639 }
1640
Daniel Dunbarf0eddb82009-03-18 02:55:38 +00001641 if (C.getArgs().hasArg(options::OPT_print_libgcc_file_name)) {
Michal Gorny7cfe4802016-10-10 12:23:40 +00001642 ToolChain::RuntimeLibType RLT = TC.GetRuntimeLibType(C.getArgs());
Leo Li23bb21c2017-08-24 01:51:51 +00001643 const llvm::Triple Triple(TC.ComputeEffectiveClangTriple(C.getArgs()));
1644 RegisterEffectiveTriple TripleRAII(TC, Triple);
Michal Gorny7cfe4802016-10-10 12:23:40 +00001645 switch (RLT) {
1646 case ToolChain::RLT_CompilerRT:
1647 llvm::outs() << TC.getCompilerRT(C.getArgs(), "builtins") << "\n";
1648 break;
1649 case ToolChain::RLT_Libgcc:
1650 llvm::outs() << GetFilePath("libgcc.a", TC) << "\n";
1651 break;
1652 }
Daniel Dunbar5e0f6af2009-03-13 00:51:18 +00001653 return false;
1654 }
1655
Daniel Dunbar1b3ec3a2009-06-16 23:25:22 +00001656 if (C.getArgs().hasArg(options::OPT_print_multi_lib)) {
Douglas Katzmana34b7bf2015-06-30 19:32:57 +00001657 for (const Multilib &Multilib : TC.getMultilibs())
1658 llvm::outs() << Multilib << "\n";
Daniel Dunbar1b3ec3a2009-06-16 23:25:22 +00001659 return false;
1660 }
1661
Jonathan Roelofs2cea1be2014-02-12 03:21:20 +00001662 if (C.getArgs().hasArg(options::OPT_print_multi_directory)) {
Douglas Katzmana34b7bf2015-06-30 19:32:57 +00001663 for (const Multilib &Multilib : TC.getMultilibs()) {
Douglas Katzman6bbffc42015-06-25 18:51:37 +00001664 if (Multilib.gccSuffix().empty())
Jonathan Roelofs2cea1be2014-02-12 03:21:20 +00001665 llvm::outs() << ".\n";
1666 else {
Douglas Katzman6bbffc42015-06-25 18:51:37 +00001667 StringRef Suffix(Multilib.gccSuffix());
Jonathan Roelofs2cea1be2014-02-12 03:21:20 +00001668 assert(Suffix.front() == '/');
1669 llvm::outs() << Suffix.substr(1) << "\n";
1670 }
Jonathan Roelofs3fa96d82014-02-12 01:36:51 +00001671 }
Jonathan Roelofs0e7ec602014-02-12 01:29:25 +00001672 return false;
1673 }
Daniel Dunbar5e0f6af2009-03-13 00:51:18 +00001674 return true;
1675}
1676
Douglas Katzmanfd528672015-06-11 15:05:22 +00001677// Display an action graph human-readably. Action A is the "sink" node
1678// and latest-occuring action. Traversal is in pre-order, visiting the
1679// inputs to each action before printing the action itself.
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001680static unsigned PrintActions1(const Compilation &C, Action *A,
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001681 std::map<Action *, unsigned> &Ids) {
Douglas Katzmanfd528672015-06-11 15:05:22 +00001682 if (Ids.count(A)) // A was already visited.
Daniel Dunbaraaf1ea62009-03-13 12:19:02 +00001683 return Ids[A];
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001684
Daniel Dunbaraaf1ea62009-03-13 12:19:02 +00001685 std::string str;
1686 llvm::raw_string_ostream os(str);
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001687
Daniel Dunbaraaf1ea62009-03-13 12:19:02 +00001688 os << Action::getClassName(A->getKind()) << ", ";
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001689 if (InputAction *IA = dyn_cast<InputAction>(A)) {
Richard Smithbd55daf2012-11-01 04:30:05 +00001690 os << "\"" << IA->getInputArg().getValue() << "\"";
Daniel Dunbaraaf1ea62009-03-13 12:19:02 +00001691 } else if (BindArchAction *BIA = dyn_cast<BindArchAction>(A)) {
Douglas Katzmanb7e8ef02015-06-25 19:37:41 +00001692 os << '"' << BIA->getArchName() << '"' << ", {"
Nico Weber5a459f82016-02-23 19:30:43 +00001693 << PrintActions1(C, *BIA->input_begin(), Ids) << "}";
Samuel Antaod06239d2016-07-15 23:13:27 +00001694 } else if (OffloadAction *OA = dyn_cast<OffloadAction>(A)) {
1695 bool IsFirst = true;
1696 OA->doOnEachDependence(
1697 [&](Action *A, const ToolChain *TC, const char *BoundArch) {
1698 // E.g. for two CUDA device dependences whose bound arch is sm_20 and
1699 // sm_35 this will generate:
1700 // "cuda-device" (nvptx64-nvidia-cuda:sm_20) {#ID}, "cuda-device"
1701 // (nvptx64-nvidia-cuda:sm_35) {#ID}
1702 if (!IsFirst)
1703 os << ", ";
1704 os << '"';
1705 if (TC)
1706 os << A->getOffloadingKindPrefix();
1707 else
1708 os << "host";
1709 os << " (";
1710 os << TC->getTriple().normalize();
1711
1712 if (BoundArch)
1713 os << ":" << BoundArch;
1714 os << ")";
1715 os << '"';
1716 os << " {" << PrintActions1(C, A, Ids) << "}";
1717 IsFirst = false;
1718 });
Daniel Dunbaraaf1ea62009-03-13 12:19:02 +00001719 } else {
Samuel Antaod06239d2016-07-15 23:13:27 +00001720 const ActionList *AL = &A->getInputs();
Artem Belevich0ff05cd2015-07-13 23:27:56 +00001721
Artem Belevich23256752015-09-22 17:23:09 +00001722 if (AL->size()) {
1723 const char *Prefix = "{";
1724 for (Action *PreRequisite : *AL) {
1725 os << Prefix << PrintActions1(C, PreRequisite, Ids);
1726 Prefix = ", ";
1727 }
1728 os << "}";
1729 } else
1730 os << "{}";
Daniel Dunbaraaf1ea62009-03-13 12:19:02 +00001731 }
1732
Samuel Antaod06239d2016-07-15 23:13:27 +00001733 // Append offload info for all options other than the offloading action
1734 // itself (e.g. (cuda-device, sm_20) or (cuda-host)).
1735 std::string offload_str;
1736 llvm::raw_string_ostream offload_os(offload_str);
1737 if (!isa<OffloadAction>(A)) {
1738 auto S = A->getOffloadingKindPrefix();
1739 if (!S.empty()) {
1740 offload_os << ", (" << S;
1741 if (A->getOffloadingArch())
1742 offload_os << ", " << A->getOffloadingArch();
1743 offload_os << ")";
1744 }
1745 }
1746
Daniel Dunbaraaf1ea62009-03-13 12:19:02 +00001747 unsigned Id = Ids.size();
1748 Ids[A] = Id;
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001749 llvm::errs() << Id << ": " << os.str() << ", "
Samuel Antaod06239d2016-07-15 23:13:27 +00001750 << types::getTypeName(A->getType()) << offload_os.str() << "\n";
Daniel Dunbaraaf1ea62009-03-13 12:19:02 +00001751
1752 return Id;
1753}
1754
Douglas Katzmanfd528672015-06-11 15:05:22 +00001755// Print the action graphs in a compilation C.
1756// For example "clang -c file1.c file2.c" is composed of two subgraphs.
Daniel Dunbareb843be2009-03-18 03:13:20 +00001757void Driver::PrintActions(const Compilation &C) const {
Douglas Katzmanb7e8ef02015-06-25 19:37:41 +00001758 std::map<Action *, unsigned> Ids;
1759 for (Action *A : C.getActions())
1760 PrintActions1(C, A, Ids);
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00001761}
1762
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001763/// Check whether the given input tree contains any compilation or
Joerg Sonnenberger5fe4a7d2011-05-06 14:05:11 +00001764/// assembly actions.
1765static bool ContainsCompileOrAssembleAction(const Action *A) {
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001766 if (isa<CompileJobAction>(A) || isa<BackendJobAction>(A) ||
Bob Wilson23a55f12014-12-21 07:00:00 +00001767 isa<AssembleJobAction>(A))
Daniel Dunbar00d3d8e2010-06-29 16:38:33 +00001768 return true;
1769
Nico Weber5a459f82016-02-23 19:30:43 +00001770 for (const Action *Input : A->inputs())
Nico Weberfb80f962015-09-19 21:36:51 +00001771 if (ContainsCompileOrAssembleAction(Input))
Daniel Dunbar00d3d8e2010-06-29 16:38:33 +00001772 return true;
1773
1774 return false;
1775}
1776
Artem Belevich5e2a3ec2015-11-17 22:28:40 +00001777void Driver::BuildUniversalActions(Compilation &C, const ToolChain &TC,
1778 const InputList &BAInputs) const {
1779 DerivedArgList &Args = C.getArgs();
1780 ActionList &Actions = C.getActions();
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001781 llvm::PrettyStackTraceString CrashInfo("Building universal build actions");
1782 // Collect the list of architectures. Duplicates are allowed, but should only
1783 // be handled once (in the order seen).
Daniel Dunbare5dc4822009-03-13 20:33:35 +00001784 llvm::StringSet<> ArchNames;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001785 SmallVector<const char *, 4> Archs;
Saleem Abdulrasool688b6bc2014-12-29 19:01:36 +00001786 for (Arg *A : Args) {
Daniel Dunbar0bfb21e2009-11-19 03:26:40 +00001787 if (A->getOption().matches(options::OPT_arch)) {
Daniel Dunbar9c3f7c42009-09-08 23:37:30 +00001788 // Validate the option here; we don't save the type here because its
1789 // particular spelling may participate in other driver choices.
1790 llvm::Triple::ArchType Arch =
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001791 tools::darwin::getArchTypeForMachOArchName(A->getValue());
Daniel Dunbar9c3f7c42009-09-08 23:37:30 +00001792 if (Arch == llvm::Triple::UnknownArch) {
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001793 Diag(clang::diag::err_drv_invalid_arch_name) << A->getAsString(Args);
Daniel Dunbar9c3f7c42009-09-08 23:37:30 +00001794 continue;
1795 }
1796
Daniel Dunbar2da02722009-03-19 07:55:12 +00001797 A->claim();
David Blaikie61b86d42014-11-19 02:56:13 +00001798 if (ArchNames.insert(A->getValue()).second)
Richard Smithbd55daf2012-11-01 04:30:05 +00001799 Archs.push_back(A->getValue());
Daniel Dunbarf479c122009-03-12 18:40:18 +00001800 }
1801 }
1802
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001803 // When there is no explicit arch for this platform, make sure we still bind
1804 // the architecture (to the default) so that -Xarch_ is handled correctly.
Daniel Dunbareb843be2009-03-18 03:13:20 +00001805 if (!Archs.size())
Daniel Dunbarc3bd9f52012-11-08 03:38:26 +00001806 Archs.push_back(Args.MakeArgString(TC.getDefaultUniversalArchName()));
Daniel Dunbarf479c122009-03-12 18:40:18 +00001807
Daniel Dunbarf479c122009-03-12 18:40:18 +00001808 ActionList SingleActions;
Justin Lebar0f3474c2016-02-11 02:00:50 +00001809 BuildActions(C, Args, BAInputs, SingleActions);
Daniel Dunbarf479c122009-03-12 18:40:18 +00001810
Daniel Dunbar6beaf512010-06-04 18:28:41 +00001811 // Add in arch bindings for every top level action, as well as lipo and
1812 // dsymutil steps if needed.
Nico Weberfb80f962015-09-19 21:36:51 +00001813 for (Action* Act : SingleActions) {
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001814 // Make sure we can lipo this kind of output. If not (and it is an actual
1815 // output) then we disallow, since we can't create an output file with the
1816 // right name without overwriting it. We could remove this oddity by just
1817 // changing the output names to include the arch, which would also fix
Daniel Dunbarf479c122009-03-12 18:40:18 +00001818 // -save-temps. Compatibility wins for now.
1819
Daniel Dunbare2ca3bd2009-03-13 17:46:02 +00001820 if (Archs.size() > 1 && !types::canLipoType(Act->getType()))
Daniel Dunbarf479c122009-03-12 18:40:18 +00001821 Diag(clang::diag::err_drv_invalid_output_with_multiple_archs)
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001822 << types::getTypeName(Act->getType());
Daniel Dunbarf479c122009-03-12 18:40:18 +00001823
1824 ActionList Inputs;
Justin Lebar41094612016-01-11 23:07:27 +00001825 for (unsigned i = 0, e = Archs.size(); i != e; ++i)
1826 Inputs.push_back(C.MakeAction<BindArchAction>(Act, Archs[i]));
Daniel Dunbarf479c122009-03-12 18:40:18 +00001827
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001828 // Lipo if necessary, we do it this way because we need to set the arch flag
1829 // so that -Xarch_ gets overwritten.
Daniel Dunbarf479c122009-03-12 18:40:18 +00001830 if (Inputs.size() == 1 || Act->getType() == types::TY_Nothing)
1831 Actions.append(Inputs.begin(), Inputs.end());
1832 else
Justin Lebar41094612016-01-11 23:07:27 +00001833 Actions.push_back(C.MakeAction<LipoJobAction>(Inputs, Act->getType()));
Daniel Dunbar6beaf512010-06-04 18:28:41 +00001834
Eric Christopher65c05fa2012-02-06 19:43:51 +00001835 // Handle debug info queries.
1836 Arg *A = Args.getLastArg(options::OPT_g_Group);
David Blaikie6f9f4eb2012-04-15 21:22:10 +00001837 if (A && !A->getOption().matches(options::OPT_g0) &&
1838 !A->getOption().matches(options::OPT_gstabs) &&
1839 ContainsCompileOrAssembleAction(Actions.back())) {
Chad Rosier62135492012-07-09 17:31:28 +00001840
David Blaikie6f9f4eb2012-04-15 21:22:10 +00001841 // Add a 'dsymutil' step if necessary, when debug info is enabled and we
1842 // have a compile input. We need to run 'dsymutil' ourselves in such cases
Eric Christopher776c26f2013-01-28 17:39:03 +00001843 // because the debug info will refer to a temporary object file which
David Blaikie6f9f4eb2012-04-15 21:22:10 +00001844 // will be removed at the end of the compilation process.
1845 if (Act->getType() == types::TY_Image) {
1846 ActionList Inputs;
1847 Inputs.push_back(Actions.back());
1848 Actions.pop_back();
Justin Lebar41094612016-01-11 23:07:27 +00001849 Actions.push_back(
1850 C.MakeAction<DsymutilJobAction>(Inputs, types::TY_dSYM));
Daniel Dunbar6beaf512010-06-04 18:28:41 +00001851 }
David Blaikie6f9f4eb2012-04-15 21:22:10 +00001852
Ben Langmuir9b9a8d32014-02-06 18:53:25 +00001853 // Verify the debug info output.
Alp Tokere9d2bfc2014-01-17 02:06:23 +00001854 if (Args.hasArg(options::OPT_verify_debug_info)) {
Justin Lebar41094612016-01-11 23:07:27 +00001855 Action* LastAction = Actions.back();
David Blaikie6f9f4eb2012-04-15 21:22:10 +00001856 Actions.pop_back();
Justin Lebar41094612016-01-11 23:07:27 +00001857 Actions.push_back(C.MakeAction<VerifyDebugInfoJobAction>(
1858 LastAction, types::TY_Nothing));
David Blaikie6f9f4eb2012-04-15 21:22:10 +00001859 }
1860 }
Daniel Dunbarf479c122009-03-12 18:40:18 +00001861 }
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00001862}
1863
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001864/// Check that the file referenced by Value exists. If it doesn't,
Hans Wennborg6ee64d52013-08-06 00:20:31 +00001865/// issue a diagnostic and return false.
Alp Toker8c8a8752013-12-03 06:53:35 +00001866static bool DiagnoseInputExistence(const Driver &D, const DerivedArgList &Args,
Hans Wennborg12f4f8b2016-04-15 01:12:32 +00001867 StringRef Value, types::ID Ty) {
Hans Wennborg6ee64d52013-08-06 00:20:31 +00001868 if (!D.getCheckInputsExist())
1869 return true;
1870
1871 // stdin always exists.
1872 if (Value == "-")
1873 return true;
1874
1875 SmallString<64> Path(Value);
1876 if (Arg *WorkDir = Args.getLastArg(options::OPT_working_directory)) {
Yaron Keren92e1b622015-03-18 10:17:07 +00001877 if (!llvm::sys::path::is_absolute(Path)) {
Hans Wennborg6ee64d52013-08-06 00:20:31 +00001878 SmallString<64> Directory(WorkDir->getValue());
1879 llvm::sys::path::append(Directory, Value);
1880 Path.assign(Directory);
1881 }
1882 }
1883
1884 if (llvm::sys::fs::exists(Twine(Path)))
1885 return true;
1886
Hans Wennborg12f4f8b2016-04-15 01:12:32 +00001887 if (D.IsCLMode()) {
1888 if (!llvm::sys::path::is_absolute(Twine(Path)) &&
1889 llvm::sys::Process::FindInEnvPath("LIB", Value))
1890 return true;
1891
1892 if (Args.hasArg(options::OPT__SLASH_link) && Ty == types::TY_Object) {
1893 // Arguments to the /link flag might cause the linker to search for object
1894 // and library files in paths we don't know about. Don't error in such
1895 // cases.
1896 return true;
1897 }
1898 }
Hans Wennborg23d26a32014-06-18 17:21:50 +00001899
Yaron Keren92e1b622015-03-18 10:17:07 +00001900 D.Diag(clang::diag::err_drv_no_such_file) << Path;
Hans Wennborg6ee64d52013-08-06 00:20:31 +00001901 return false;
1902}
1903
Chad Rosierecdede82011-08-12 22:08:57 +00001904// Construct a the list of inputs and their types.
Hans Wennborg55362852014-05-02 22:55:30 +00001905void Driver::BuildInputs(const ToolChain &TC, DerivedArgList &Args,
Chad Rosierecdede82011-08-12 22:08:57 +00001906 InputList &Inputs) const {
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001907 // Track the current user specified (-x) input. We also explicitly track the
1908 // argument used to set the type; we only want to claim the type when we
1909 // actually use it, so we warn about unused -x arguments.
Daniel Dunbarc5a5ac52009-03-13 17:57:10 +00001910 types::ID InputType = types::TY_Nothing;
Craig Topper92fc2df2014-05-17 16:56:41 +00001911 Arg *InputTypeArg = nullptr;
Daniel Dunbarc5a5ac52009-03-13 17:57:10 +00001912
Hans Wennborg0d0b19c2013-08-12 18:34:17 +00001913 // The last /TC or /TP option sets the input type to C or C++ globally.
Ehsan Akhgaric249abb2014-09-12 21:44:24 +00001914 if (Arg *TCTP = Args.getLastArgNoClaim(options::OPT__SLASH_TC,
1915 options::OPT__SLASH_TP)) {
Hans Wennborg6ee64d52013-08-06 00:20:31 +00001916 InputTypeArg = TCTP;
Hans Wennborg0d0b19c2013-08-12 18:34:17 +00001917 InputType = TCTP->getOption().matches(options::OPT__SLASH_TC)
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001918 ? types::TY_C
1919 : types::TY_CXX;
Hans Wennborg6ee64d52013-08-06 00:20:31 +00001920
Richard Smith0aef3052017-02-18 01:14:43 +00001921 Arg *Previous = nullptr;
Hans Wennborg0d0b19c2013-08-12 18:34:17 +00001922 bool ShowNote = false;
Richard Smith0aef3052017-02-18 01:14:43 +00001923 for (Arg *A : Args.filtered(options::OPT__SLASH_TC, options::OPT__SLASH_TP)) {
1924 if (Previous) {
1925 Diag(clang::diag::warn_drv_overriding_flag_option)
1926 << Previous->getSpelling() << A->getSpelling();
1927 ShowNote = true;
1928 }
1929 Previous = A;
Hans Wennborg6ee64d52013-08-06 00:20:31 +00001930 }
Hans Wennborg0d0b19c2013-08-12 18:34:17 +00001931 if (ShowNote)
1932 Diag(clang::diag::note_drv_t_option_is_global);
Hans Wennborg6ee64d52013-08-06 00:20:31 +00001933
1934 // No driver mode exposes -x and /TC or /TP; we don't support mixing them.
1935 assert(!Args.hasArg(options::OPT_x) && "-x and /TC or /TP is not allowed");
1936 }
1937
Saleem Abdulrasool688b6bc2014-12-29 19:01:36 +00001938 for (Arg *A : Args) {
Michael J. Spencerad3ccc32012-08-20 21:41:17 +00001939 if (A->getOption().getKind() == Option::InputClass) {
Richard Smithbd55daf2012-11-01 04:30:05 +00001940 const char *Value = A->getValue();
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00001941 types::ID Ty = types::TY_INVALID;
1942
1943 // Infer the input type if necessary.
Daniel Dunbarc5a5ac52009-03-13 17:57:10 +00001944 if (InputType == types::TY_Nothing) {
1945 // If there was an explicit arg for this, claim it.
1946 if (InputTypeArg)
1947 InputTypeArg->claim();
1948
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00001949 // stdin must be handled specially.
1950 if (memcmp(Value, "-", 2) == 0) {
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001951 // If running with -E, treat as a C input (this changes the builtin
1952 // macros, for example). This may be overridden by -ObjC below.
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00001953 //
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001954 // Otherwise emit an error but still use a valid type to avoid
1955 // spurious errors (e.g., no inputs).
Hans Wennborg70850d82013-07-18 20:29:38 +00001956 if (!Args.hasArgNoClaim(options::OPT_E) && !CCCIsCPP())
Hans Wennborgcfdd8b52014-01-29 01:04:40 +00001957 Diag(IsCLMode() ? clang::diag::err_drv_unknown_stdin_type_clang_cl
1958 : clang::diag::err_drv_unknown_stdin_type);
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00001959 Ty = types::TY_C;
1960 } else {
Joerg Sonnenbergerbdbdf702011-03-16 22:45:02 +00001961 // Otherwise lookup by extension.
1962 // Fallback is C if invoked as C preprocessor or Object otherwise.
1963 // We use a host hook here because Darwin at least has its own
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001964 // idea of what .s is.
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00001965 if (const char *Ext = strrchr(Value, '.'))
Daniel Dunbarcc7df6c2010-08-02 05:43:56 +00001966 Ty = TC.LookupTypeForExtension(Ext + 1);
Daniel Dunbarea9f0322009-03-20 23:39:23 +00001967
Joerg Sonnenbergerbdbdf702011-03-16 22:45:02 +00001968 if (Ty == types::TY_INVALID) {
Hans Wennborg70850d82013-07-18 20:29:38 +00001969 if (CCCIsCPP())
Joerg Sonnenbergerbdbdf702011-03-16 22:45:02 +00001970 Ty = types::TY_C;
1971 else
1972 Ty = types::TY_Object;
1973 }
Daniel Dunbar0ac94452010-02-17 20:32:58 +00001974
1975 // If the driver is invoked as C++ compiler (like clang++ or c++) it
1976 // should autodetect some input files as C++ for g++ compatibility.
Hans Wennborg70850d82013-07-18 20:29:38 +00001977 if (CCCIsCXX()) {
Daniel Dunbar0ac94452010-02-17 20:32:58 +00001978 types::ID OldTy = Ty;
1979 Ty = types::lookupCXXTypeForCType(Ty);
1980
1981 if (Ty != OldTy)
1982 Diag(clang::diag::warn_drv_treating_input_as_cxx)
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001983 << getTypeName(OldTy) << getTypeName(Ty);
Daniel Dunbar0ac94452010-02-17 20:32:58 +00001984 }
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00001985 }
1986
Daniel Dunbar82b22102009-05-18 21:47:54 +00001987 // -ObjC and -ObjC++ override the default language, but only for "source
1988 // files". We just treat everything that isn't a linker input as a
1989 // source file.
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001990 //
Daniel Dunbar82b22102009-05-18 21:47:54 +00001991 // FIXME: Clean this up if we move the phase sequence into the type.
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00001992 if (Ty != types::TY_Object) {
1993 if (Args.hasArg(options::OPT_ObjC))
1994 Ty = types::TY_ObjC;
1995 else if (Args.hasArg(options::OPT_ObjCXX))
1996 Ty = types::TY_ObjCXX;
1997 }
1998 } else {
1999 assert(InputTypeArg && "InputType set w/o InputTypeArg");
Ehsan Akhgari7e954ea2014-09-12 18:15:10 +00002000 if (!InputTypeArg->getOption().matches(options::OPT_x)) {
2001 // If emulating cl.exe, make sure that /TC and /TP don't affect input
2002 // object files.
2003 const char *Ext = strrchr(Value, '.');
2004 if (Ext && TC.LookupTypeForExtension(Ext + 1) == types::TY_Object)
2005 Ty = types::TY_Object;
2006 }
2007 if (Ty == types::TY_INVALID) {
2008 Ty = InputType;
2009 InputTypeArg->claim();
2010 }
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00002011 }
2012
Hans Wennborg12f4f8b2016-04-15 01:12:32 +00002013 if (DiagnoseInputExistence(*this, Args, Value, Ty))
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00002014 Inputs.push_back(std::make_pair(Ty, A));
2015
Hans Wennborg6ee64d52013-08-06 00:20:31 +00002016 } else if (A->getOption().matches(options::OPT__SLASH_Tc)) {
2017 StringRef Value = A->getValue();
Hans Wennborg12f4f8b2016-04-15 01:12:32 +00002018 if (DiagnoseInputExistence(*this, Args, Value, types::TY_C)) {
David Blaikie0aaa7622017-01-13 17:34:15 +00002019 Arg *InputArg = MakeInputArg(Args, *Opts, A->getValue());
Hans Wennborg6ee64d52013-08-06 00:20:31 +00002020 Inputs.push_back(std::make_pair(types::TY_C, InputArg));
2021 }
2022 A->claim();
2023 } else if (A->getOption().matches(options::OPT__SLASH_Tp)) {
2024 StringRef Value = A->getValue();
Hans Wennborg12f4f8b2016-04-15 01:12:32 +00002025 if (DiagnoseInputExistence(*this, Args, Value, types::TY_CXX)) {
David Blaikie0aaa7622017-01-13 17:34:15 +00002026 Arg *InputArg = MakeInputArg(Args, *Opts, A->getValue());
Hans Wennborg6ee64d52013-08-06 00:20:31 +00002027 Inputs.push_back(std::make_pair(types::TY_CXX, InputArg));
2028 }
2029 A->claim();
Michael J. Spencer66e2b202012-10-19 22:37:06 +00002030 } else if (A->getOption().hasFlag(options::LinkerInput)) {
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00002031 // Just treat as object type, we could make a special type for this if
2032 // necessary.
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00002033 Inputs.push_back(std::make_pair(types::TY_Object, A));
2034
Daniel Dunbar0bfb21e2009-11-19 03:26:40 +00002035 } else if (A->getOption().matches(options::OPT_x)) {
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00002036 InputTypeArg = A;
Richard Smithbd55daf2012-11-01 04:30:05 +00002037 InputType = types::lookupTypeForTypeSpecifier(A->getValue());
Chad Rosier706c2352012-04-07 00:01:31 +00002038 A->claim();
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00002039
2040 // Follow gcc behavior and treat as linker input for invalid -x
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00002041 // options. Its not clear why we shouldn't just revert to unknown; but
Michael J. Spencer1a4fe8c2010-12-17 21:22:33 +00002042 // this isn't very important, we might as well be bug compatible.
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00002043 if (!InputType) {
Richard Smithbd55daf2012-11-01 04:30:05 +00002044 Diag(clang::diag::err_drv_unknown_language) << A->getValue();
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00002045 InputType = types::TY_Object;
2046 }
Hans Wennborg091f1b62017-01-27 17:09:41 +00002047 } else if (A->getOption().getID() == options::OPT__SLASH_U) {
2048 assert(A->getNumValues() == 1 && "The /U option has one value.");
2049 StringRef Val = A->getValue(0);
2050 if (Val.find_first_of("/\\") != StringRef::npos) {
2051 // Warn about e.g. "/Users/me/myfile.c".
2052 Diag(diag::warn_slash_u_filename) << Val;
2053 Diag(diag::note_use_dashdash);
2054 }
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00002055 }
2056 }
Hans Wennborg70850d82013-07-18 20:29:38 +00002057 if (CCCIsCPP() && Inputs.empty()) {
Joerg Sonnenbergerb86f5f42011-03-06 23:31:01 +00002058 // If called as standalone preprocessor, stdin is processed
2059 // if no other input is present.
David Blaikie0aaa7622017-01-13 17:34:15 +00002060 Arg *A = MakeInputArg(Args, *Opts, "-");
Joerg Sonnenbergerb86f5f42011-03-06 23:31:01 +00002061 Inputs.push_back(std::make_pair(types::TY_C, A));
2062 }
Chad Rosierecdede82011-08-12 22:08:57 +00002063}
2064
Samuel Antao64e965e2016-09-30 15:34:19 +00002065namespace {
2066/// Provides a convenient interface for different programming models to generate
2067/// the required device actions.
2068class OffloadingActionBuilder final {
2069 /// Flag used to trace errors in the builder.
2070 bool IsValid = false;
2071
2072 /// The compilation that is using this builder.
2073 Compilation &C;
2074
Samuel Antao64e965e2016-09-30 15:34:19 +00002075 /// Map between an input argument and the offload kinds used to process it.
2076 std::map<const Arg *, unsigned> InputArgToOffloadKindMap;
2077
2078 /// Builder interface. It doesn't build anything or keep any state.
2079 class DeviceActionBuilder {
2080 public:
2081 typedef llvm::SmallVector<phases::ID, phases::MaxNumberOfPhases> PhasesTy;
2082
2083 enum ActionBuilderReturnCode {
2084 // The builder acted successfully on the current action.
2085 ABRT_Success,
2086 // The builder didn't have to act on the current action.
2087 ABRT_Inactive,
2088 // The builder was successful and requested the host action to not be
2089 // generated.
2090 ABRT_Ignore_Host,
2091 };
2092
2093 protected:
2094 /// Compilation associated with this builder.
2095 Compilation &C;
2096
2097 /// Tool chains associated with this builder. The same programming
2098 /// model may have associated one or more tool chains.
2099 SmallVector<const ToolChain *, 2> ToolChains;
2100
2101 /// The derived arguments associated with this builder.
2102 DerivedArgList &Args;
2103
2104 /// The inputs associated with this builder.
2105 const Driver::InputList &Inputs;
2106
2107 /// The associated offload kind.
2108 Action::OffloadKind AssociatedOffloadKind = Action::OFK_None;
2109
2110 public:
2111 DeviceActionBuilder(Compilation &C, DerivedArgList &Args,
2112 const Driver::InputList &Inputs,
2113 Action::OffloadKind AssociatedOffloadKind)
2114 : C(C), Args(Args), Inputs(Inputs),
2115 AssociatedOffloadKind(AssociatedOffloadKind) {}
2116 virtual ~DeviceActionBuilder() {}
2117
2118 /// Fill up the array \a DA with all the device dependences that should be
2119 /// added to the provided host action \a HostAction. By default it is
2120 /// inactive.
2121 virtual ActionBuilderReturnCode
Samuel Antao28c4f182016-10-27 17:08:03 +00002122 getDeviceDependences(OffloadAction::DeviceDependences &DA,
2123 phases::ID CurPhase, phases::ID FinalPhase,
2124 PhasesTy &Phases) {
Samuel Antao64e965e2016-09-30 15:34:19 +00002125 return ABRT_Inactive;
2126 }
2127
2128 /// Update the state to include the provided host action \a HostAction as a
2129 /// dependency of the current device action. By default it is inactive.
2130 virtual ActionBuilderReturnCode addDeviceDepences(Action *HostAction) {
2131 return ABRT_Inactive;
2132 }
2133
2134 /// Append top level actions generated by the builder. Return true if errors
2135 /// were found.
2136 virtual void appendTopLevelActions(ActionList &AL) {}
2137
2138 /// Append linker actions generated by the builder. Return true if errors
2139 /// were found.
2140 virtual void appendLinkDependences(OffloadAction::DeviceDependences &DA) {}
2141
2142 /// Initialize the builder. Return true if any initialization errors are
2143 /// found.
2144 virtual bool initialize() { return false; }
2145
Samuel Antao69d6f312016-10-27 17:50:43 +00002146 /// Return true if the builder can use bundling/unbundling.
2147 virtual bool canUseBundlerUnbundler() const { return false; }
2148
Samuel Antao64e965e2016-09-30 15:34:19 +00002149 /// Return true if this builder is valid. We have a valid builder if we have
2150 /// associated device tool chains.
2151 bool isValid() { return !ToolChains.empty(); }
2152
2153 /// Return the associated offload kind.
2154 Action::OffloadKind getAssociatedOffloadKind() {
2155 return AssociatedOffloadKind;
2156 }
2157 };
2158
Yaxun Liu3af038b2018-05-30 00:49:10 +00002159 /// Base class for CUDA/HIP action builder. It injects device code in
2160 /// the host backend action.
2161 class CudaActionBuilderBase : public DeviceActionBuilder {
2162 protected:
Samuel Antao64e965e2016-09-30 15:34:19 +00002163 /// Flags to signal if the user requested host-only or device-only
2164 /// compilation.
2165 bool CompileHostOnly = false;
2166 bool CompileDeviceOnly = false;
2167
2168 /// List of GPU architectures to use in this compilation.
2169 SmallVector<CudaArch, 4> GpuArchList;
2170
2171 /// The CUDA actions for the current input.
2172 ActionList CudaDeviceActions;
2173
2174 /// The CUDA fat binary if it was generated for the current input.
2175 Action *CudaFatBinary = nullptr;
2176
2177 /// Flag that is set to true if this builder acted on the current input.
2178 bool IsActive = false;
Yaxun Liu3af038b2018-05-30 00:49:10 +00002179 public:
2180 CudaActionBuilderBase(Compilation &C, DerivedArgList &Args,
2181 const Driver::InputList &Inputs,
2182 Action::OffloadKind OFKind)
2183 : DeviceActionBuilder(C, Args, Inputs, OFKind) {}
Samuel Antao64e965e2016-09-30 15:34:19 +00002184
Yaxun Liu3af038b2018-05-30 00:49:10 +00002185 ActionBuilderReturnCode addDeviceDepences(Action *HostAction) override {
2186 // While generating code for CUDA, we only depend on the host input action
2187 // to trigger the creation of all the CUDA device actions.
2188
2189 // If we are dealing with an input action, replicate it for each GPU
2190 // architecture. If we are in host-only mode we return 'success' so that
2191 // the host uses the CUDA offload kind.
2192 if (auto *IA = dyn_cast<InputAction>(HostAction)) {
2193 assert(!GpuArchList.empty() &&
2194 "We should have at least one GPU architecture.");
2195
2196 // If the host input is not CUDA or HIP, we don't need to bother about
2197 // this input.
2198 if (IA->getType() != types::TY_CUDA &&
2199 IA->getType() != types::TY_HIP) {
2200 // The builder will ignore this input.
2201 IsActive = false;
2202 return ABRT_Inactive;
2203 }
2204
2205 // Set the flag to true, so that the builder acts on the current input.
2206 IsActive = true;
2207
2208 if (CompileHostOnly)
2209 return ABRT_Success;
2210
2211 // Replicate inputs for each GPU architecture.
2212 auto Ty = IA->getType() == types::TY_HIP ? types::TY_HIP_DEVICE
2213 : types::TY_CUDA_DEVICE;
2214 for (unsigned I = 0, E = GpuArchList.size(); I != E; ++I) {
2215 CudaDeviceActions.push_back(
2216 C.MakeAction<InputAction>(IA->getInputArg(), Ty));
2217 }
2218
2219 return ABRT_Success;
2220 }
2221
2222 // If this is an unbundling action use it as is for each CUDA toolchain.
2223 if (auto *UA = dyn_cast<OffloadUnbundlingJobAction>(HostAction)) {
2224 CudaDeviceActions.clear();
2225 for (auto Arch : GpuArchList) {
2226 CudaDeviceActions.push_back(UA);
2227 UA->registerDependentActionInfo(ToolChains[0], CudaArchToString(Arch),
2228 AssociatedOffloadKind);
2229 }
2230 return ABRT_Success;
2231 }
2232
2233 return IsActive ? ABRT_Success : ABRT_Inactive;
2234 }
2235
2236 void appendTopLevelActions(ActionList &AL) override {
2237 // Utility to append actions to the top level list.
2238 auto AddTopLevel = [&](Action *A, CudaArch BoundArch) {
2239 OffloadAction::DeviceDependences Dep;
2240 Dep.add(*A, *ToolChains.front(), CudaArchToString(BoundArch),
2241 AssociatedOffloadKind);
2242 AL.push_back(C.MakeAction<OffloadAction>(Dep, A->getType()));
2243 };
2244
2245 // If we have a fat binary, add it to the list.
2246 if (CudaFatBinary) {
2247 AddTopLevel(CudaFatBinary, CudaArch::UNKNOWN);
2248 CudaDeviceActions.clear();
2249 CudaFatBinary = nullptr;
2250 return;
2251 }
2252
2253 if (CudaDeviceActions.empty())
2254 return;
2255
2256 // If we have CUDA actions at this point, that's because we have a have
2257 // partial compilation, so we should have an action for each GPU
2258 // architecture.
2259 assert(CudaDeviceActions.size() == GpuArchList.size() &&
2260 "Expecting one action per GPU architecture.");
2261 assert(ToolChains.size() == 1 &&
2262 "Expecting to have a sing CUDA toolchain.");
2263 for (unsigned I = 0, E = GpuArchList.size(); I != E; ++I)
2264 AddTopLevel(CudaDeviceActions[I], GpuArchList[I]);
2265
2266 CudaDeviceActions.clear();
2267 }
2268
2269 bool initialize() override {
2270 assert(AssociatedOffloadKind == Action::OFK_Cuda ||
2271 AssociatedOffloadKind == Action::OFK_HIP);
2272
2273 // We don't need to support CUDA.
2274 if (AssociatedOffloadKind == Action::OFK_Cuda &&
2275 !C.hasOffloadToolChain<Action::OFK_Cuda>())
2276 return false;
2277
2278 // We don't need to support HIP.
2279 if (AssociatedOffloadKind == Action::OFK_HIP &&
2280 !C.hasOffloadToolChain<Action::OFK_HIP>())
2281 return false;
2282
2283 const ToolChain *HostTC = C.getSingleOffloadToolChain<Action::OFK_Host>();
2284 assert(HostTC && "No toolchain for host compilation.");
2285 if (HostTC->getTriple().isNVPTX() ||
2286 HostTC->getTriple().getArch() == llvm::Triple::amdgcn) {
2287 // We do not support targeting NVPTX/AMDGCN for host compilation. Throw
2288 // an error and abort pipeline construction early so we don't trip
2289 // asserts that assume device-side compilation.
2290 C.getDriver().Diag(diag::err_drv_cuda_host_arch)
2291 << HostTC->getTriple().getArchName();
2292 return true;
2293 }
2294
2295 ToolChains.push_back(
2296 AssociatedOffloadKind == Action::OFK_Cuda
2297 ? C.getSingleOffloadToolChain<Action::OFK_Cuda>()
2298 : C.getSingleOffloadToolChain<Action::OFK_HIP>());
2299
2300 Arg *PartialCompilationArg = Args.getLastArg(
2301 options::OPT_cuda_host_only, options::OPT_cuda_device_only,
2302 options::OPT_cuda_compile_host_device);
2303 CompileHostOnly = PartialCompilationArg &&
2304 PartialCompilationArg->getOption().matches(
2305 options::OPT_cuda_host_only);
2306 CompileDeviceOnly = PartialCompilationArg &&
2307 PartialCompilationArg->getOption().matches(
2308 options::OPT_cuda_device_only);
2309
2310 // Collect all cuda_gpu_arch parameters, removing duplicates.
2311 std::set<CudaArch> GpuArchs;
2312 bool Error = false;
2313 for (Arg *A : Args) {
2314 if (!(A->getOption().matches(options::OPT_cuda_gpu_arch_EQ) ||
2315 A->getOption().matches(options::OPT_no_cuda_gpu_arch_EQ)))
2316 continue;
2317 A->claim();
2318
2319 const StringRef ArchStr = A->getValue();
2320 if (A->getOption().matches(options::OPT_no_cuda_gpu_arch_EQ) &&
2321 ArchStr == "all") {
2322 GpuArchs.clear();
2323 continue;
2324 }
2325 CudaArch Arch = StringToCudaArch(ArchStr);
2326 if (Arch == CudaArch::UNKNOWN) {
2327 C.getDriver().Diag(clang::diag::err_drv_cuda_bad_gpu_arch) << ArchStr;
2328 Error = true;
2329 } else if (A->getOption().matches(options::OPT_cuda_gpu_arch_EQ))
2330 GpuArchs.insert(Arch);
2331 else if (A->getOption().matches(options::OPT_no_cuda_gpu_arch_EQ))
2332 GpuArchs.erase(Arch);
2333 else
2334 llvm_unreachable("Unexpected option.");
2335 }
2336
2337 // Collect list of GPUs remaining in the set.
2338 for (CudaArch Arch : GpuArchs)
2339 GpuArchList.push_back(Arch);
2340
2341 // Default to sm_20 which is the lowest common denominator for
2342 // supported GPUs. sm_20 code should work correctly, if
2343 // suboptimally, on all newer GPUs.
2344 if (GpuArchList.empty())
2345 GpuArchList.push_back(CudaArch::SM_20);
2346
2347 return Error;
2348 }
2349 };
2350
2351 /// \brief CUDA action builder. It injects device code in the host backend
2352 /// action.
2353 class CudaActionBuilder final : public CudaActionBuilderBase {
Samuel Antao64e965e2016-09-30 15:34:19 +00002354 public:
2355 CudaActionBuilder(Compilation &C, DerivedArgList &Args,
2356 const Driver::InputList &Inputs)
Yaxun Liu3af038b2018-05-30 00:49:10 +00002357 : CudaActionBuilderBase(C, Args, Inputs, Action::OFK_Cuda) {}
Samuel Antao64e965e2016-09-30 15:34:19 +00002358
2359 ActionBuilderReturnCode
Samuel Antao28c4f182016-10-27 17:08:03 +00002360 getDeviceDependences(OffloadAction::DeviceDependences &DA,
2361 phases::ID CurPhase, phases::ID FinalPhase,
2362 PhasesTy &Phases) override {
Samuel Antao64e965e2016-09-30 15:34:19 +00002363 if (!IsActive)
2364 return ABRT_Inactive;
2365
2366 // If we don't have more CUDA actions, we don't have any dependences to
2367 // create for the host.
2368 if (CudaDeviceActions.empty())
2369 return ABRT_Success;
2370
2371 assert(CudaDeviceActions.size() == GpuArchList.size() &&
2372 "Expecting one action per GPU architecture.");
2373 assert(!CompileHostOnly &&
2374 "Not expecting CUDA actions in host-only compilation.");
2375
2376 // If we are generating code for the device or we are in a backend phase,
2377 // we attempt to generate the fat binary. We compile each arch to ptx and
2378 // assemble to cubin, then feed the cubin *and* the ptx into a device
2379 // "link" action, which uses fatbinary to combine these cubins into one
2380 // fatbin. The fatbin is then an input to the host action if not in
2381 // device-only mode.
2382 if (CompileDeviceOnly || CurPhase == phases::Backend) {
2383 ActionList DeviceActions;
2384 for (unsigned I = 0, E = GpuArchList.size(); I != E; ++I) {
2385 // Produce the device action from the current phase up to the assemble
2386 // phase.
2387 for (auto Ph : Phases) {
2388 // Skip the phases that were already dealt with.
2389 if (Ph < CurPhase)
2390 continue;
2391 // We have to be consistent with the host final phase.
2392 if (Ph > FinalPhase)
2393 break;
2394
2395 CudaDeviceActions[I] = C.getDriver().ConstructPhaseAction(
Artem Belevichecb178b2018-03-21 22:22:59 +00002396 C, Args, Ph, CudaDeviceActions[I], Action::OFK_Cuda);
Samuel Antao64e965e2016-09-30 15:34:19 +00002397
2398 if (Ph == phases::Assemble)
2399 break;
2400 }
2401
2402 // If we didn't reach the assemble phase, we can't generate the fat
2403 // binary. We don't need to generate the fat binary if we are not in
2404 // device-only mode.
2405 if (!isa<AssembleJobAction>(CudaDeviceActions[I]) ||
2406 CompileDeviceOnly)
2407 continue;
2408
2409 Action *AssembleAction = CudaDeviceActions[I];
2410 assert(AssembleAction->getType() == types::TY_Object);
2411 assert(AssembleAction->getInputs().size() == 1);
2412
2413 Action *BackendAction = AssembleAction->getInputs()[0];
2414 assert(BackendAction->getType() == types::TY_PP_Asm);
2415
2416 for (auto &A : {AssembleAction, BackendAction}) {
2417 OffloadAction::DeviceDependences DDep;
2418 DDep.add(*A, *ToolChains.front(), CudaArchToString(GpuArchList[I]),
2419 Action::OFK_Cuda);
2420 DeviceActions.push_back(
2421 C.MakeAction<OffloadAction>(DDep, A->getType()));
2422 }
2423 }
2424
2425 // We generate the fat binary if we have device input actions.
2426 if (!DeviceActions.empty()) {
2427 CudaFatBinary =
2428 C.MakeAction<LinkJobAction>(DeviceActions, types::TY_CUDA_FATBIN);
2429
2430 if (!CompileDeviceOnly) {
2431 DA.add(*CudaFatBinary, *ToolChains.front(), /*BoundArch=*/nullptr,
2432 Action::OFK_Cuda);
2433 // Clear the fat binary, it is already a dependence to an host
2434 // action.
2435 CudaFatBinary = nullptr;
2436 }
2437
2438 // Remove the CUDA actions as they are already connected to an host
2439 // action or fat binary.
2440 CudaDeviceActions.clear();
2441 }
2442
2443 // We avoid creating host action in device-only mode.
2444 return CompileDeviceOnly ? ABRT_Ignore_Host : ABRT_Success;
Samuel Antao5b1a89a2016-10-27 00:53:34 +00002445 } else if (CurPhase > phases::Backend) {
2446 // If we are past the backend phase and still have a device action, we
2447 // don't have to do anything as this action is already a device
2448 // top-level action.
2449 return ABRT_Success;
Samuel Antao64e965e2016-09-30 15:34:19 +00002450 }
2451
2452 assert(CurPhase < phases::Backend && "Generating single CUDA "
2453 "instructions should only occur "
2454 "before the backend phase!");
2455
2456 // By default, we produce an action for each device arch.
2457 for (Action *&A : CudaDeviceActions)
2458 A = C.getDriver().ConstructPhaseAction(C, Args, CurPhase, A);
2459
2460 return ABRT_Success;
2461 }
Yaxun Liu3af038b2018-05-30 00:49:10 +00002462 };
2463 /// \brief HIP action builder. It injects device code in the host backend
2464 /// action.
2465 class HIPActionBuilder final : public CudaActionBuilderBase {
2466 /// The linker inputs obtained for each device arch.
2467 SmallVector<ActionList, 8> DeviceLinkerInputs;
Samuel Antao64e965e2016-09-30 15:34:19 +00002468
Yaxun Liu3af038b2018-05-30 00:49:10 +00002469 public:
2470 HIPActionBuilder(Compilation &C, DerivedArgList &Args,
2471 const Driver::InputList &Inputs)
2472 : CudaActionBuilderBase(C, Args, Inputs, Action::OFK_HIP) {}
Samuel Antao64e965e2016-09-30 15:34:19 +00002473
Yaxun Liu3af038b2018-05-30 00:49:10 +00002474 bool canUseBundlerUnbundler() const override { return true; }
Samuel Antao64e965e2016-09-30 15:34:19 +00002475
Yaxun Liu3af038b2018-05-30 00:49:10 +00002476 ActionBuilderReturnCode
2477 getDeviceDependences(OffloadAction::DeviceDependences &DA,
2478 phases::ID CurPhase, phases::ID FinalPhase,
2479 PhasesTy &Phases) override {
2480 // amdgcn does not support linking of object files, therefore we skip
2481 // backend and assemble phases to output LLVM IR.
2482 if (CudaDeviceActions.empty() || CurPhase == phases::Backend ||
2483 CurPhase == phases::Assemble)
2484 return ABRT_Success;
2485
2486 assert((CurPhase == phases::Link ||
2487 CudaDeviceActions.size() == GpuArchList.size()) &&
2488 "Expecting one action per GPU architecture.");
2489 assert(!CompileHostOnly &&
2490 "Not expecting CUDA actions in host-only compilation.");
2491
2492 // Save CudaDeviceActions to DeviceLinkerInputs for each GPU subarch.
2493 // This happens to each device action originated from each input file.
2494 // Later on, device actions in DeviceLinkerInputs are used to create
2495 // device link actions in appendLinkDependences and the created device
2496 // link actions are passed to the offload action as device dependence.
2497 if (CurPhase == phases::Link) {
2498 DeviceLinkerInputs.resize(CudaDeviceActions.size());
2499 auto LI = DeviceLinkerInputs.begin();
2500 for (auto *A : CudaDeviceActions) {
2501 LI->push_back(A);
2502 ++LI;
Samuel Antao64e965e2016-09-30 15:34:19 +00002503 }
2504
Yaxun Liu3af038b2018-05-30 00:49:10 +00002505 // We will pass the device action as a host dependence, so we don't
2506 // need to do anything else with them.
2507 CudaDeviceActions.clear();
Samuel Antao64e965e2016-09-30 15:34:19 +00002508 return ABRT_Success;
2509 }
2510
Yaxun Liu3af038b2018-05-30 00:49:10 +00002511 // By default, we produce an action for each device arch.
2512 for (Action *&A : CudaDeviceActions)
2513 A = C.getDriver().ConstructPhaseAction(C, Args, CurPhase, A,
2514 AssociatedOffloadKind);
2515
2516 return ABRT_Success;
Samuel Antao64e965e2016-09-30 15:34:19 +00002517 }
2518
Yaxun Liu3af038b2018-05-30 00:49:10 +00002519 void appendLinkDependences(OffloadAction::DeviceDependences &DA) override {
2520 // Append a new link action for each device.
2521 unsigned I = 0;
2522 for (auto &LI : DeviceLinkerInputs) {
2523 auto *DeviceLinkAction =
2524 C.MakeAction<LinkJobAction>(LI, types::TY_Image);
2525 DA.add(*DeviceLinkAction, *ToolChains[0],
2526 CudaArchToString(GpuArchList[I]), AssociatedOffloadKind);
2527 ++I;
Samuel Antao64e965e2016-09-30 15:34:19 +00002528 }
Samuel Antao64e965e2016-09-30 15:34:19 +00002529 }
2530 };
2531
Samuel Antao28c4f182016-10-27 17:08:03 +00002532 /// OpenMP action builder. The host bitcode is passed to the device frontend
2533 /// and all the device linked images are passed to the host link phase.
2534 class OpenMPActionBuilder final : public DeviceActionBuilder {
2535 /// The OpenMP actions for the current input.
2536 ActionList OpenMPDeviceActions;
2537
2538 /// The linker inputs obtained for each toolchain.
2539 SmallVector<ActionList, 8> DeviceLinkerInputs;
2540
2541 public:
2542 OpenMPActionBuilder(Compilation &C, DerivedArgList &Args,
2543 const Driver::InputList &Inputs)
2544 : DeviceActionBuilder(C, Args, Inputs, Action::OFK_OpenMP) {}
2545
2546 ActionBuilderReturnCode
2547 getDeviceDependences(OffloadAction::DeviceDependences &DA,
2548 phases::ID CurPhase, phases::ID FinalPhase,
2549 PhasesTy &Phases) override {
2550
2551 // We should always have an action for each input.
2552 assert(OpenMPDeviceActions.size() == ToolChains.size() &&
2553 "Number of OpenMP actions and toolchains do not match.");
2554
2555 // The host only depends on device action in the linking phase, when all
2556 // the device images have to be embedded in the host image.
2557 if (CurPhase == phases::Link) {
2558 assert(ToolChains.size() == DeviceLinkerInputs.size() &&
2559 "Toolchains and linker inputs sizes do not match.");
2560 auto LI = DeviceLinkerInputs.begin();
2561 for (auto *A : OpenMPDeviceActions) {
2562 LI->push_back(A);
2563 ++LI;
2564 }
2565
2566 // We passed the device action as a host dependence, so we don't need to
2567 // do anything else with them.
2568 OpenMPDeviceActions.clear();
2569 return ABRT_Success;
2570 }
2571
2572 // By default, we produce an action for each device arch.
2573 for (Action *&A : OpenMPDeviceActions)
2574 A = C.getDriver().ConstructPhaseAction(C, Args, CurPhase, A);
2575
2576 return ABRT_Success;
2577 }
2578
2579 ActionBuilderReturnCode addDeviceDepences(Action *HostAction) override {
2580
2581 // If this is an input action replicate it for each OpenMP toolchain.
2582 if (auto *IA = dyn_cast<InputAction>(HostAction)) {
2583 OpenMPDeviceActions.clear();
2584 for (unsigned I = 0; I < ToolChains.size(); ++I)
2585 OpenMPDeviceActions.push_back(
2586 C.MakeAction<InputAction>(IA->getInputArg(), IA->getType()));
2587 return ABRT_Success;
2588 }
2589
Samuel Antaofab4f372016-10-27 18:00:51 +00002590 // If this is an unbundling action use it as is for each OpenMP toolchain.
2591 if (auto *UA = dyn_cast<OffloadUnbundlingJobAction>(HostAction)) {
2592 OpenMPDeviceActions.clear();
2593 for (unsigned I = 0; I < ToolChains.size(); ++I) {
2594 OpenMPDeviceActions.push_back(UA);
2595 UA->registerDependentActionInfo(
2596 ToolChains[I], /*BoundArch=*/StringRef(), Action::OFK_OpenMP);
2597 }
2598 return ABRT_Success;
2599 }
2600
Samuel Antao28c4f182016-10-27 17:08:03 +00002601 // When generating code for OpenMP we use the host compile phase result as
2602 // a dependence to the device compile phase so that it can learn what
2603 // declarations should be emitted. However, this is not the only use for
2604 // the host action, so we prevent it from being collapsed.
2605 if (isa<CompileJobAction>(HostAction)) {
2606 HostAction->setCannotBeCollapsedWithNextDependentAction();
2607 assert(ToolChains.size() == OpenMPDeviceActions.size() &&
2608 "Toolchains and device action sizes do not match.");
2609 OffloadAction::HostDependence HDep(
2610 *HostAction, *C.getSingleOffloadToolChain<Action::OFK_Host>(),
2611 /*BoundArch=*/nullptr, Action::OFK_OpenMP);
2612 auto TC = ToolChains.begin();
2613 for (Action *&A : OpenMPDeviceActions) {
2614 assert(isa<CompileJobAction>(A));
2615 OffloadAction::DeviceDependences DDep;
2616 DDep.add(*A, **TC, /*BoundArch=*/nullptr, Action::OFK_OpenMP);
2617 A = C.MakeAction<OffloadAction>(HDep, DDep);
2618 ++TC;
2619 }
2620 }
2621 return ABRT_Success;
2622 }
2623
Samuel Antao69d6f312016-10-27 17:50:43 +00002624 void appendTopLevelActions(ActionList &AL) override {
2625 if (OpenMPDeviceActions.empty())
2626 return;
2627
2628 // We should always have an action for each input.
2629 assert(OpenMPDeviceActions.size() == ToolChains.size() &&
2630 "Number of OpenMP actions and toolchains do not match.");
2631
2632 // Append all device actions followed by the proper offload action.
2633 auto TI = ToolChains.begin();
2634 for (auto *A : OpenMPDeviceActions) {
2635 OffloadAction::DeviceDependences Dep;
2636 Dep.add(*A, **TI, /*BoundArch=*/nullptr, Action::OFK_OpenMP);
2637 AL.push_back(C.MakeAction<OffloadAction>(Dep, A->getType()));
2638 ++TI;
2639 }
2640 // We no longer need the action stored in this builder.
2641 OpenMPDeviceActions.clear();
2642 }
2643
Samuel Antao28c4f182016-10-27 17:08:03 +00002644 void appendLinkDependences(OffloadAction::DeviceDependences &DA) override {
2645 assert(ToolChains.size() == DeviceLinkerInputs.size() &&
2646 "Toolchains and linker inputs sizes do not match.");
2647
2648 // Append a new link action for each device.
2649 auto TC = ToolChains.begin();
2650 for (auto &LI : DeviceLinkerInputs) {
2651 auto *DeviceLinkAction =
2652 C.MakeAction<LinkJobAction>(LI, types::TY_Image);
2653 DA.add(*DeviceLinkAction, **TC, /*BoundArch=*/nullptr,
2654 Action::OFK_OpenMP);
2655 ++TC;
2656 }
2657 }
2658
2659 bool initialize() override {
2660 // Get the OpenMP toolchains. If we don't get any, the action builder will
2661 // know there is nothing to do related to OpenMP offloading.
2662 auto OpenMPTCRange = C.getOffloadToolChains<Action::OFK_OpenMP>();
2663 for (auto TI = OpenMPTCRange.first, TE = OpenMPTCRange.second; TI != TE;
2664 ++TI)
2665 ToolChains.push_back(TI->second);
2666
2667 DeviceLinkerInputs.resize(ToolChains.size());
2668 return false;
2669 }
Samuel Antao69d6f312016-10-27 17:50:43 +00002670
2671 bool canUseBundlerUnbundler() const override {
2672 // OpenMP should use bundled files whenever possible.
2673 return true;
2674 }
Samuel Antao28c4f182016-10-27 17:08:03 +00002675 };
2676
2677 ///
2678 /// TODO: Add the implementation for other specialized builders here.
2679 ///
Samuel Antao64e965e2016-09-30 15:34:19 +00002680
2681 /// Specialized builders being used by this offloading action builder.
2682 SmallVector<DeviceActionBuilder *, 4> SpecializedBuilders;
2683
Samuel Antao69d6f312016-10-27 17:50:43 +00002684 /// Flag set to true if all valid builders allow file bundling/unbundling.
2685 bool CanUseBundler;
2686
Samuel Antao64e965e2016-09-30 15:34:19 +00002687public:
2688 OffloadingActionBuilder(Compilation &C, DerivedArgList &Args,
2689 const Driver::InputList &Inputs)
Samuel Antao10e905c2016-10-27 01:08:58 +00002690 : C(C) {
Samuel Antao64e965e2016-09-30 15:34:19 +00002691 // Create a specialized builder for each device toolchain.
2692
2693 IsValid = true;
2694
2695 // Create a specialized builder for CUDA.
2696 SpecializedBuilders.push_back(new CudaActionBuilder(C, Args, Inputs));
2697
Yaxun Liu3af038b2018-05-30 00:49:10 +00002698 // Create a specialized builder for HIP.
2699 SpecializedBuilders.push_back(new HIPActionBuilder(C, Args, Inputs));
2700
Samuel Antao28c4f182016-10-27 17:08:03 +00002701 // Create a specialized builder for OpenMP.
2702 SpecializedBuilders.push_back(new OpenMPActionBuilder(C, Args, Inputs));
2703
Samuel Antao64e965e2016-09-30 15:34:19 +00002704 //
2705 // TODO: Build other specialized builders here.
2706 //
2707
Samuel Antao69d6f312016-10-27 17:50:43 +00002708 // Initialize all the builders, keeping track of errors. If all valid
2709 // builders agree that we can use bundling, set the flag to true.
2710 unsigned ValidBuilders = 0u;
2711 unsigned ValidBuildersSupportingBundling = 0u;
2712 for (auto *SB : SpecializedBuilders) {
Samuel Antao64e965e2016-09-30 15:34:19 +00002713 IsValid = IsValid && !SB->initialize();
Samuel Antao69d6f312016-10-27 17:50:43 +00002714
2715 // Update the counters if the builder is valid.
2716 if (SB->isValid()) {
2717 ++ValidBuilders;
2718 if (SB->canUseBundlerUnbundler())
2719 ++ValidBuildersSupportingBundling;
2720 }
2721 }
2722 CanUseBundler =
2723 ValidBuilders && ValidBuilders == ValidBuildersSupportingBundling;
Artem Belevichf981e30b2016-08-02 22:37:47 +00002724 }
Justin Lebardc3c5042016-04-19 02:27:07 +00002725
Samuel Antao64e965e2016-09-30 15:34:19 +00002726 ~OffloadingActionBuilder() {
2727 for (auto *SB : SpecializedBuilders)
2728 delete SB;
Samuel Antaod06239d2016-07-15 23:13:27 +00002729 }
Artem Belevich0ff05cd2015-07-13 23:27:56 +00002730
Samuel Antao64e965e2016-09-30 15:34:19 +00002731 /// Generate an action that adds device dependences (if any) to a host action.
2732 /// If no device dependence actions exist, just return the host action \a
2733 /// HostAction. If an error is found or if no builder requires the host action
2734 /// to be generated, return nullptr.
2735 Action *
2736 addDeviceDependencesToHostAction(Action *HostAction, const Arg *InputArg,
2737 phases::ID CurPhase, phases::ID FinalPhase,
2738 DeviceActionBuilder::PhasesTy &Phases) {
2739 if (!IsValid)
2740 return nullptr;
Justin Lebar7bf77982016-01-11 23:27:13 +00002741
Samuel Antao64e965e2016-09-30 15:34:19 +00002742 if (SpecializedBuilders.empty())
2743 return HostAction;
2744
2745 assert(HostAction && "Invalid host action!");
2746
2747 OffloadAction::DeviceDependences DDeps;
2748 // Check if all the programming models agree we should not emit the host
2749 // action. Also, keep track of the offloading kinds employed.
2750 auto &OffloadKind = InputArgToOffloadKindMap[InputArg];
2751 unsigned InactiveBuilders = 0u;
2752 unsigned IgnoringBuilders = 0u;
2753 for (auto *SB : SpecializedBuilders) {
2754 if (!SB->isValid()) {
2755 ++InactiveBuilders;
2756 continue;
2757 }
2758
Samuel Antao28c4f182016-10-27 17:08:03 +00002759 auto RetCode =
2760 SB->getDeviceDependences(DDeps, CurPhase, FinalPhase, Phases);
Samuel Antao64e965e2016-09-30 15:34:19 +00002761
2762 // If the builder explicitly says the host action should be ignored,
2763 // we need to increment the variable that tracks the builders that request
2764 // the host object to be ignored.
2765 if (RetCode == DeviceActionBuilder::ABRT_Ignore_Host)
2766 ++IgnoringBuilders;
2767
2768 // Unless the builder was inactive for this action, we have to record the
2769 // offload kind because the host will have to use it.
2770 if (RetCode != DeviceActionBuilder::ABRT_Inactive)
2771 OffloadKind |= SB->getAssociatedOffloadKind();
2772 }
2773
2774 // If all builders agree that the host object should be ignored, just return
2775 // nullptr.
2776 if (IgnoringBuilders &&
2777 SpecializedBuilders.size() == (InactiveBuilders + IgnoringBuilders))
2778 return nullptr;
2779
2780 if (DDeps.getActions().empty())
2781 return HostAction;
2782
2783 // We have dependences we need to bundle together. We use an offload action
2784 // for that.
2785 OffloadAction::HostDependence HDep(
2786 *HostAction, *C.getSingleOffloadToolChain<Action::OFK_Host>(),
2787 /*BoundArch=*/nullptr, DDeps);
2788 return C.MakeAction<OffloadAction>(HDep, DDeps);
Artem Belevich0ff05cd2015-07-13 23:27:56 +00002789 }
2790
Samuel Antao64e965e2016-09-30 15:34:19 +00002791 /// Generate an action that adds a host dependence to a device action. The
2792 /// results will be kept in this action builder. Return true if an error was
2793 /// found.
Samuel Antaofab4f372016-10-27 18:00:51 +00002794 bool addHostDependenceToDeviceActions(Action *&HostAction,
Samuel Antao64e965e2016-09-30 15:34:19 +00002795 const Arg *InputArg) {
2796 if (!IsValid)
2797 return true;
Artem Belevich0ff05cd2015-07-13 23:27:56 +00002798
Samuel Antaofab4f372016-10-27 18:00:51 +00002799 // If we are supporting bundling/unbundling and the current action is an
2800 // input action of non-source file, we replace the host action by the
2801 // unbundling action. The bundler tool has the logic to detect if an input
2802 // is a bundle or not and if the input is not a bundle it assumes it is a
2803 // host file. Therefore it is safe to create an unbundling action even if
2804 // the input is not a bundle.
2805 if (CanUseBundler && isa<InputAction>(HostAction) &&
2806 InputArg->getOption().getKind() == llvm::opt::Option::InputClass &&
2807 !types::isSrcFile(HostAction->getType())) {
2808 auto UnbundlingHostAction =
2809 C.MakeAction<OffloadUnbundlingJobAction>(HostAction);
2810 UnbundlingHostAction->registerDependentActionInfo(
2811 C.getSingleOffloadToolChain<Action::OFK_Host>(),
Yaxun Liu470b8332018-06-06 19:44:10 +00002812 /*BoundArch=*/"all", Action::OFK_Host);
Samuel Antaofab4f372016-10-27 18:00:51 +00002813 HostAction = UnbundlingHostAction;
2814 }
2815
Samuel Antao64e965e2016-09-30 15:34:19 +00002816 assert(HostAction && "Invalid host action!");
Artem Belevich0ff05cd2015-07-13 23:27:56 +00002817
Samuel Antao64e965e2016-09-30 15:34:19 +00002818 // Register the offload kinds that are used.
2819 auto &OffloadKind = InputArgToOffloadKindMap[InputArg];
2820 for (auto *SB : SpecializedBuilders) {
2821 if (!SB->isValid())
2822 continue;
Artem Belevich0ff05cd2015-07-13 23:27:56 +00002823
Samuel Antao64e965e2016-09-30 15:34:19 +00002824 auto RetCode = SB->addDeviceDepences(HostAction);
Artem Belevich0ff05cd2015-07-13 23:27:56 +00002825
Samuel Antao64e965e2016-09-30 15:34:19 +00002826 // Host dependences for device actions are not compatible with that same
2827 // action being ignored.
2828 assert(RetCode != DeviceActionBuilder::ABRT_Ignore_Host &&
2829 "Host dependence not expected to be ignored.!");
Samuel Antaod06239d2016-07-15 23:13:27 +00002830
Samuel Antao64e965e2016-09-30 15:34:19 +00002831 // Unless the builder was inactive for this action, we have to record the
2832 // offload kind because the host will have to use it.
2833 if (RetCode != DeviceActionBuilder::ABRT_Inactive)
2834 OffloadKind |= SB->getAssociatedOffloadKind();
2835 }
Artem Belevich0ff05cd2015-07-13 23:27:56 +00002836
Samuel Antao64e965e2016-09-30 15:34:19 +00002837 return false;
2838 }
2839
Samuel Antao69d6f312016-10-27 17:50:43 +00002840 /// Add the offloading top level actions to the provided action list. This
2841 /// function can replace the host action by a bundling action if the
2842 /// programming models allow it.
Samuel Antao64e965e2016-09-30 15:34:19 +00002843 bool appendTopLevelActions(ActionList &AL, Action *HostAction,
2844 const Arg *InputArg) {
Samuel Antao69d6f312016-10-27 17:50:43 +00002845 // Get the device actions to be appended.
2846 ActionList OffloadAL;
Samuel Antao64e965e2016-09-30 15:34:19 +00002847 for (auto *SB : SpecializedBuilders) {
2848 if (!SB->isValid())
2849 continue;
Samuel Antao69d6f312016-10-27 17:50:43 +00002850 SB->appendTopLevelActions(OffloadAL);
Samuel Antao64e965e2016-09-30 15:34:19 +00002851 }
2852
Samuel Antao69d6f312016-10-27 17:50:43 +00002853 // If we can use the bundler, replace the host action by the bundling one in
2854 // the resulting list. Otherwise, just append the device actions.
2855 if (CanUseBundler && !OffloadAL.empty()) {
2856 // Add the host action to the list in order to create the bundling action.
2857 OffloadAL.push_back(HostAction);
2858
2859 // We expect that the host action was just appended to the action list
2860 // before this method was called.
2861 assert(HostAction == AL.back() && "Host action not in the list??");
2862 HostAction = C.MakeAction<OffloadBundlingJobAction>(OffloadAL);
2863 AL.back() = HostAction;
2864 } else
2865 AL.append(OffloadAL.begin(), OffloadAL.end());
2866
Samuel Antao64e965e2016-09-30 15:34:19 +00002867 // Propagate to the current host action (if any) the offload information
2868 // associated with the current input.
2869 if (HostAction)
2870 HostAction->propagateHostOffloadInfo(InputArgToOffloadKindMap[InputArg],
2871 /*BoundArch=*/nullptr);
Samuel Antao64e965e2016-09-30 15:34:19 +00002872 return false;
Artem Belevich0ff05cd2015-07-13 23:27:56 +00002873 }
Artem Belevich5bde4e02015-07-20 20:02:54 +00002874
Samuel Antao64e965e2016-09-30 15:34:19 +00002875 /// Processes the host linker action. This currently consists of replacing it
2876 /// with an offload action if there are device link objects and propagate to
2877 /// the host action all the offload kinds used in the current compilation. The
2878 /// resulting action is returned.
2879 Action *processHostLinkAction(Action *HostAction) {
2880 // Add all the dependences from the device linking actions.
2881 OffloadAction::DeviceDependences DDeps;
2882 for (auto *SB : SpecializedBuilders) {
2883 if (!SB->isValid())
2884 continue;
Justin Lebar21e5d4f2016-01-14 21:41:27 +00002885
Samuel Antao64e965e2016-09-30 15:34:19 +00002886 SB->appendLinkDependences(DDeps);
Justin Lebar21e5d4f2016-01-14 21:41:27 +00002887 }
Samuel Antaod06239d2016-07-15 23:13:27 +00002888
Samuel Antao64e965e2016-09-30 15:34:19 +00002889 // Calculate all the offload kinds used in the current compilation.
2890 unsigned ActiveOffloadKinds = 0u;
2891 for (auto &I : InputArgToOffloadKindMap)
2892 ActiveOffloadKinds |= I.second;
2893
2894 // If we don't have device dependencies, we don't have to create an offload
2895 // action.
2896 if (DDeps.getActions().empty()) {
2897 // Propagate all the active kinds to host action. Given that it is a link
2898 // action it is assumed to depend on all actions generated so far.
2899 HostAction->propagateHostOffloadInfo(ActiveOffloadKinds,
2900 /*BoundArch=*/nullptr);
2901 return HostAction;
2902 }
2903
2904 // Create the offload action with all dependences. When an offload action
2905 // is created the kinds are propagated to the host action, so we don't have
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00002906 // to do that explicitly here.
Samuel Antao64e965e2016-09-30 15:34:19 +00002907 OffloadAction::HostDependence HDep(
2908 *HostAction, *C.getSingleOffloadToolChain<Action::OFK_Host>(),
2909 /*BoundArch*/ nullptr, ActiveOffloadKinds);
2910 return C.MakeAction<OffloadAction>(HDep, DDeps);
2911 }
2912};
2913} // anonymous namespace.
Artem Belevich0ff05cd2015-07-13 23:27:56 +00002914
Justin Lebar0f3474c2016-02-11 02:00:50 +00002915void Driver::BuildActions(Compilation &C, DerivedArgList &Args,
2916 const InputList &Inputs, ActionList &Actions) const {
Chad Rosierecdede82011-08-12 22:08:57 +00002917 llvm::PrettyStackTraceString CrashInfo("Building compilation actions");
Joerg Sonnenbergerb86f5f42011-03-06 23:31:01 +00002918
Daniel Dunbar34c41872009-03-13 00:17:48 +00002919 if (!SuppressMissingInputWarning && Inputs.empty()) {
Daniel Dunbarbfeec742009-03-12 23:55:14 +00002920 Diag(clang::diag::err_drv_no_input_files);
2921 return;
2922 }
2923
Chad Rosier7742b5d2011-07-27 23:36:45 +00002924 Arg *FinalPhaseArg;
2925 phases::ID FinalPhase = getFinalPhase(Args, &FinalPhaseArg);
Daniel Dunbarbfeec742009-03-12 23:55:14 +00002926
Bob Haarmanaaf51912017-02-27 19:40:19 +00002927 if (FinalPhase == phases::Link) {
2928 if (Args.hasArg(options::OPT_emit_llvm))
2929 Diag(clang::diag::err_drv_emit_llvm_link);
2930 if (IsCLMode() && LTOMode != LTOK_None &&
2931 !Args.getLastArgValue(options::OPT_fuse_ld_EQ).equals_lower("lld"))
2932 Diag(clang::diag::err_drv_lto_without_lld);
Rafael Espindolae8025642013-08-25 14:27:09 +00002933 }
2934
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00002935 // Reject -Z* at the top level, these options should never have been exposed
2936 // by gcc.
Daniel Dunbardd765242009-03-26 16:12:09 +00002937 if (Arg *A = Args.getLastArg(options::OPT_Z_Joined))
Daniel Dunbar0e759942009-03-20 06:14:23 +00002938 Diag(clang::diag::err_drv_use_of_Z_option) << A->getAsString(Args);
Daniel Dunbarbfeec742009-03-12 23:55:14 +00002939
Hans Wennborg13b7fe72013-08-12 23:26:25 +00002940 // Diagnose misuse of /Fo.
2941 if (Arg *A = Args.getLastArg(options::OPT__SLASH_Fo)) {
Hans Wennborg13b7fe72013-08-12 23:26:25 +00002942 StringRef V = A->getValue();
Hans Wennborg61647532014-11-17 19:16:36 +00002943 if (Inputs.size() > 1 && !V.empty() &&
2944 !llvm::sys::path::is_separator(V.back())) {
Hans Wennborg13b7fe72013-08-12 23:26:25 +00002945 // Check whether /Fo tries to name an output file for multiple inputs.
Hans Wennborg9c1659b2013-10-18 22:49:04 +00002946 Diag(clang::diag::err_drv_out_file_argument_with_multiple_sources)
Douglas Katzmana67e50c2015-06-26 15:47:46 +00002947 << A->getSpelling() << V;
Hans Wennborg13b7fe72013-08-12 23:26:25 +00002948 Args.eraseArg(options::OPT__SLASH_Fo);
2949 }
2950 }
2951
Hans Wennborg9c1659b2013-10-18 22:49:04 +00002952 // Diagnose misuse of /Fa.
2953 if (Arg *A = Args.getLastArg(options::OPT__SLASH_Fa)) {
2954 StringRef V = A->getValue();
Hans Wennborg61647532014-11-17 19:16:36 +00002955 if (Inputs.size() > 1 && !V.empty() &&
2956 !llvm::sys::path::is_separator(V.back())) {
Hans Wennborg9c1659b2013-10-18 22:49:04 +00002957 // Check whether /Fa tries to name an asm file for multiple inputs.
2958 Diag(clang::diag::err_drv_out_file_argument_with_multiple_sources)
Douglas Katzmana67e50c2015-06-26 15:47:46 +00002959 << A->getSpelling() << V;
Hans Wennborg9c1659b2013-10-18 22:49:04 +00002960 Args.eraseArg(options::OPT__SLASH_Fa);
2961 }
2962 }
2963
Ehsan Akhgari81f36b72014-09-11 18:16:21 +00002964 // Diagnose misuse of /o.
2965 if (Arg *A = Args.getLastArg(options::OPT__SLASH_o)) {
2966 if (A->getValue()[0] == '\0') {
2967 // It has to have a value.
2968 Diag(clang::diag::err_drv_missing_argument) << A->getSpelling() << 1;
2969 Args.eraseArg(options::OPT__SLASH_o);
2970 }
2971 }
2972
Nico Weber2ca4be92016-03-01 23:16:44 +00002973 // Diagnose unsupported forms of /Yc /Yu. Ignore /Yc/Yu for now if:
2974 // * no filename after it
2975 // * both /Yc and /Yu passed but with different filenames
2976 // * corresponding file not also passed as /FI
2977 Arg *YcArg = Args.getLastArg(options::OPT__SLASH_Yc);
2978 Arg *YuArg = Args.getLastArg(options::OPT__SLASH_Yu);
2979 if (YcArg && YcArg->getValue()[0] == '\0') {
2980 Diag(clang::diag::warn_drv_ycyu_no_arg_clang_cl) << YcArg->getSpelling();
2981 Args.eraseArg(options::OPT__SLASH_Yc);
2982 YcArg = nullptr;
2983 }
2984 if (YuArg && YuArg->getValue()[0] == '\0') {
2985 Diag(clang::diag::warn_drv_ycyu_no_arg_clang_cl) << YuArg->getSpelling();
2986 Args.eraseArg(options::OPT__SLASH_Yu);
2987 YuArg = nullptr;
2988 }
2989 if (YcArg && YuArg && strcmp(YcArg->getValue(), YuArg->getValue()) != 0) {
2990 Diag(clang::diag::warn_drv_ycyu_different_arg_clang_cl);
2991 Args.eraseArg(options::OPT__SLASH_Yc);
2992 Args.eraseArg(options::OPT__SLASH_Yu);
2993 YcArg = YuArg = nullptr;
2994 }
Nico Weber2ca4be92016-03-01 23:16:44 +00002995 if (YcArg && Inputs.size() > 1) {
2996 Diag(clang::diag::warn_drv_yc_multiple_inputs_clang_cl);
2997 Args.eraseArg(options::OPT__SLASH_Yc);
2998 YcArg = nullptr;
2999 }
3000 if (Args.hasArg(options::OPT__SLASH_Y_)) {
3001 // /Y- disables all pch handling. Rather than check for it everywhere,
3002 // just remove clang-cl pch-related flags here.
3003 Args.eraseArg(options::OPT__SLASH_Fp);
3004 Args.eraseArg(options::OPT__SLASH_Yc);
3005 Args.eraseArg(options::OPT__SLASH_Yu);
3006 YcArg = YuArg = nullptr;
3007 }
Nico Weber2ca4be92016-03-01 23:16:44 +00003008
Samuel Antao64e965e2016-09-30 15:34:19 +00003009 // Builder to be used to build offloading actions.
3010 OffloadingActionBuilder OffloadBuilder(C, Args, Inputs);
Samuel Antaod06239d2016-07-15 23:13:27 +00003011
Daniel Dunbar65229332009-03-13 11:38:42 +00003012 // Construct the actions to perform.
3013 ActionList LinkerInputs;
Alp Toker965f8822013-11-27 05:22:15 +00003014
Matthew Curtis7ab8b2b2013-03-07 12:32:26 +00003015 llvm::SmallVector<phases::ID, phases::MaxNumberOfPhases> PL;
Artem Belevich5bde4e02015-07-20 20:02:54 +00003016 for (auto &I : Inputs) {
3017 types::ID InputType = I.first;
3018 const Arg *InputArg = I.second;
Daniel Dunbar65229332009-03-13 11:38:42 +00003019
Matthew Curtis7ab8b2b2013-03-07 12:32:26 +00003020 PL.clear();
3021 types::getCompilationPhases(InputType, PL);
Daniel Dunbar65229332009-03-13 11:38:42 +00003022
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00003023 // If the first step comes after the final phase we are doing as part of
3024 // this compilation, warn the user about it.
Matthew Curtis7ab8b2b2013-03-07 12:32:26 +00003025 phases::ID InitialPhase = PL[0];
Daniel Dunbar65229332009-03-13 11:38:42 +00003026 if (InitialPhase > FinalPhase) {
Martin Storsjo665c7a42018-05-04 06:05:58 +00003027 if (InputArg->isClaimed())
3028 continue;
3029
Daniel Dunbaradc5c7c2009-03-19 07:57:08 +00003030 // Claim here to avoid the more general unused warning.
3031 InputArg->claim();
Daniel Dunbar07806ca2009-09-17 04:13:26 +00003032
Daniel Dunbar2db3e732011-04-20 15:44:48 +00003033 // Suppress all unused style warnings with -Qunused-arguments
3034 if (Args.hasArg(options::OPT_Qunused_arguments))
3035 continue;
3036
Richard Smith403f76e2012-08-06 04:09:06 +00003037 // Special case when final phase determined by binary name, rather than
3038 // by a command-line argument with a corresponding Arg.
Hans Wennborg70850d82013-07-18 20:29:38 +00003039 if (CCCIsCPP())
Richard Smith403f76e2012-08-06 04:09:06 +00003040 Diag(clang::diag::warn_drv_input_file_unused_by_cpp)
Douglas Katzmana67e50c2015-06-26 15:47:46 +00003041 << InputArg->getAsString(Args) << getPhaseName(InitialPhase);
Daniel Dunbar07806ca2009-09-17 04:13:26 +00003042 // Special case '-E' warning on a previously preprocessed file to make
3043 // more sense.
Richard Smith403f76e2012-08-06 04:09:06 +00003044 else if (InitialPhase == phases::Compile &&
3045 FinalPhase == phases::Preprocess &&
3046 getPreprocessedType(InputType) == types::TY_INVALID)
Daniel Dunbar07806ca2009-09-17 04:13:26 +00003047 Diag(clang::diag::warn_drv_preprocessed_input_file_unused)
Douglas Katzmana67e50c2015-06-26 15:47:46 +00003048 << InputArg->getAsString(Args) << !!FinalPhaseArg
3049 << (FinalPhaseArg ? FinalPhaseArg->getOption().getName() : "");
Daniel Dunbar07806ca2009-09-17 04:13:26 +00003050 else
3051 Diag(clang::diag::warn_drv_input_file_unused)
Douglas Katzmana67e50c2015-06-26 15:47:46 +00003052 << InputArg->getAsString(Args) << getPhaseName(InitialPhase)
3053 << !!FinalPhaseArg
3054 << (FinalPhaseArg ? FinalPhaseArg->getOption().getName() : "");
Daniel Dunbar65229332009-03-13 11:38:42 +00003055 continue;
3056 }
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00003057
Nico Weberad2d8f32016-04-21 19:59:10 +00003058 if (YcArg) {
3059 // Add a separate precompile phase for the compile phase.
3060 if (FinalPhase >= phases::Compile) {
Richard Smith8cd452d2016-08-30 18:55:16 +00003061 const types::ID HeaderType = lookupHeaderTypeForSourceType(InputType);
Nico Weberad2d8f32016-04-21 19:59:10 +00003062 llvm::SmallVector<phases::ID, phases::MaxNumberOfPhases> PCHPL;
Richard Smith8cd452d2016-08-30 18:55:16 +00003063 types::getCompilationPhases(HeaderType, PCHPL);
Nico Weberad2d8f32016-04-21 19:59:10 +00003064 // Build the pipeline for the pch file.
Richard Smith8cd452d2016-08-30 18:55:16 +00003065 Action *ClangClPch =
Erich Keane76675de2018-07-05 17:22:13 +00003066 C.MakeAction<InputAction>(*InputArg, HeaderType);
Nico Weberad2d8f32016-04-21 19:59:10 +00003067 for (phases::ID Phase : PCHPL)
3068 ClangClPch = ConstructPhaseAction(C, Args, Phase, ClangClPch);
3069 assert(ClangClPch);
3070 Actions.push_back(ClangClPch);
3071 // The driver currently exits after the first failed command. This
3072 // relies on that behavior, to make sure if the pch generation fails,
3073 // the main compilation won't run.
Hans Wennborg08c5a7b2018-06-25 13:23:49 +00003074 // FIXME: If the main compilation fails, the PCH generation should
3075 // probably not be considered successful either.
Nico Weberad2d8f32016-04-21 19:59:10 +00003076 }
3077 }
3078
Daniel Dunbar65229332009-03-13 11:38:42 +00003079 // Build the pipeline for this file.
Justin Lebar41094612016-01-11 23:07:27 +00003080 Action *Current = C.MakeAction<InputAction>(*InputArg, InputType);
Samuel Antao64e965e2016-09-30 15:34:19 +00003081
3082 // Use the current host action in any of the offloading actions, if
3083 // required.
3084 if (OffloadBuilder.addHostDependenceToDeviceActions(Current, InputArg))
3085 break;
3086
Douglas Katzmana67e50c2015-06-26 15:47:46 +00003087 for (SmallVectorImpl<phases::ID>::iterator i = PL.begin(), e = PL.end();
3088 i != e; ++i) {
Matthew Curtis7ab8b2b2013-03-07 12:32:26 +00003089 phases::ID Phase = *i;
Daniel Dunbar65229332009-03-13 11:38:42 +00003090
3091 // We are done if this step is past what the user requested.
3092 if (Phase > FinalPhase)
3093 break;
3094
Samuel Antao64e965e2016-09-30 15:34:19 +00003095 // Add any offload action the host action depends on.
3096 Current = OffloadBuilder.addDeviceDependencesToHostAction(
3097 Current, InputArg, Phase, FinalPhase, PL);
3098 if (!Current)
3099 break;
3100
Daniel Dunbar65229332009-03-13 11:38:42 +00003101 // Queue linker inputs.
3102 if (Phase == phases::Link) {
Matthew Curtis7ab8b2b2013-03-07 12:32:26 +00003103 assert((i + 1) == e && "linking must be final compilation step.");
Justin Lebar41094612016-01-11 23:07:27 +00003104 LinkerInputs.push_back(Current);
3105 Current = nullptr;
Daniel Dunbar65229332009-03-13 11:38:42 +00003106 break;
3107 }
3108
Samuel Antao64e965e2016-09-30 15:34:19 +00003109 // Otherwise construct the appropriate action.
3110 auto *NewCurrent = ConstructPhaseAction(C, Args, Phase, Current);
3111
3112 // We didn't create a new action, so we will just move to the next phase.
3113 if (NewCurrent == Current)
Daniel Dunbar13864952009-03-24 20:17:30 +00003114 continue;
3115
Samuel Antao64e965e2016-09-30 15:34:19 +00003116 Current = NewCurrent;
Artem Belevich0ff05cd2015-07-13 23:27:56 +00003117
Samuel Antao64e965e2016-09-30 15:34:19 +00003118 // Use the current host action in any of the offloading actions, if
3119 // required.
3120 if (OffloadBuilder.addHostDependenceToDeviceActions(Current, InputArg))
3121 break;
Artem Belevich0ff05cd2015-07-13 23:27:56 +00003122
Daniel Dunbar65229332009-03-13 11:38:42 +00003123 if (Current->getType() == types::TY_Nothing)
3124 break;
3125 }
3126
Samuel Antao64e965e2016-09-30 15:34:19 +00003127 // If we ended with something, add to the output list.
3128 if (Current)
Justin Lebar41094612016-01-11 23:07:27 +00003129 Actions.push_back(Current);
Samuel Antao64e965e2016-09-30 15:34:19 +00003130
3131 // Add any top level actions generated for offloading.
3132 OffloadBuilder.appendTopLevelActions(Actions, Current, InputArg);
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00003133 }
Daniel Dunbar65229332009-03-13 11:38:42 +00003134
Samuel Antao64e965e2016-09-30 15:34:19 +00003135 // Add a link action if necessary.
Samuel Antaod06239d2016-07-15 23:13:27 +00003136 if (!LinkerInputs.empty()) {
Samuel Antao64e965e2016-09-30 15:34:19 +00003137 Action *LA = C.MakeAction<LinkJobAction>(LinkerInputs, types::TY_Image);
3138 LA = OffloadBuilder.processHostLinkAction(LA);
3139 Actions.push_back(LA);
Samuel Antaod06239d2016-07-15 23:13:27 +00003140 }
Daniel Dunbarc7a67b72009-12-22 23:19:32 +00003141
3142 // If we are linking, claim any options which are obviously only used for
3143 // compilation.
Hans Wennborga8ef14f2013-09-17 00:03:41 +00003144 if (FinalPhase == phases::Link && PL.size() == 1) {
Daniel Dunbarc7a67b72009-12-22 23:19:32 +00003145 Args.ClaimAllArgs(options::OPT_CompileOnly_Group);
Hans Wennborga8ef14f2013-09-17 00:03:41 +00003146 Args.ClaimAllArgs(options::OPT_cl_compile_Group);
3147 }
3148
3149 // Claim ignored clang-cl options.
3150 Args.ClaimAllArgs(options::OPT_cl_ignored_Group);
Artem Belevichbaae0932015-07-28 21:01:30 +00003151
Justin Lebardc3c5042016-04-19 02:27:07 +00003152 // Claim --cuda-host-only and --cuda-compile-host-device, which may be passed
3153 // to non-CUDA compilations and should not trigger warnings there.
Artem Belevichbaae0932015-07-28 21:01:30 +00003154 Args.ClaimAllArgs(options::OPT_cuda_host_only);
Justin Lebardc3c5042016-04-19 02:27:07 +00003155 Args.ClaimAllArgs(options::OPT_cuda_compile_host_device);
Daniel Dunbar65229332009-03-13 11:38:42 +00003156}
3157
Artem Belevichecb178b2018-03-21 22:22:59 +00003158Action *Driver::ConstructPhaseAction(
3159 Compilation &C, const ArgList &Args, phases::ID Phase, Action *Input,
3160 Action::OffloadKind TargetDeviceOffloadKind) const {
Daniel Dunbar2608c542009-03-18 01:38:48 +00003161 llvm::PrettyStackTraceString CrashInfo("Constructing phase actions");
Samuel Antao64e965e2016-09-30 15:34:19 +00003162
3163 // Some types skip the assembler phase (e.g., llvm-bc), but we can't
3164 // encode this in the steps because the intermediate type depends on
3165 // arguments. Just special case here.
3166 if (Phase == phases::Assemble && Input->getType() != types::TY_PP_Asm)
3167 return Input;
3168
Daniel Dunbar65229332009-03-13 11:38:42 +00003169 // Build the appropriate action.
3170 switch (Phase) {
Douglas Katzmana67e50c2015-06-26 15:47:46 +00003171 case phases::Link:
3172 llvm_unreachable("link action invalid here.");
Daniel Dunbar65229332009-03-13 11:38:42 +00003173 case phases::Preprocess: {
Daniel Dunbard67a3222009-03-30 06:36:42 +00003174 types::ID OutputTy;
3175 // -{M, MM} alter the output type.
Daniel Dunbar86aed7d2010-12-08 21:33:40 +00003176 if (Args.hasArg(options::OPT_M, options::OPT_MM)) {
Daniel Dunbard67a3222009-03-30 06:36:42 +00003177 OutputTy = types::TY_Dependencies;
3178 } else {
David Blaikie5d577a22012-06-29 22:03:56 +00003179 OutputTy = Input->getType();
3180 if (!Args.hasFlag(options::OPT_frewrite_includes,
Justin Bognerce8245b2014-06-24 08:01:01 +00003181 options::OPT_fno_rewrite_includes, false) &&
Richard Smith86a3ef52017-06-09 21:24:02 +00003182 !Args.hasFlag(options::OPT_frewrite_imports,
3183 options::OPT_fno_rewrite_imports, false) &&
Justin Bognerce8245b2014-06-24 08:01:01 +00003184 !CCGenDiagnostics)
David Blaikie5d577a22012-06-29 22:03:56 +00003185 OutputTy = types::getPreprocessedType(OutputTy);
Daniel Dunbard67a3222009-03-30 06:36:42 +00003186 assert(OutputTy != types::TY_INVALID &&
3187 "Cannot preprocess this input type!");
3188 }
Justin Lebar41094612016-01-11 23:07:27 +00003189 return C.MakeAction<PreprocessJobAction>(Input, OutputTy);
Daniel Dunbar65229332009-03-13 11:38:42 +00003190 }
Aaron Ballman1f10cc52012-07-31 01:21:00 +00003191 case phases::Precompile: {
Richard Smithdd4ad3d2016-08-30 19:06:26 +00003192 types::ID OutputTy = getPrecompiledType(Input->getType());
3193 assert(OutputTy != types::TY_INVALID &&
3194 "Cannot precompile this input type!");
Aaron Ballman1f10cc52012-07-31 01:21:00 +00003195 if (Args.hasArg(options::OPT_fsyntax_only)) {
3196 // Syntax checks should not emit a PCH file
3197 OutputTy = types::TY_Nothing;
3198 }
Justin Lebar41094612016-01-11 23:07:27 +00003199 return C.MakeAction<PrecompileJobAction>(Input, OutputTy);
Aaron Ballman1f10cc52012-07-31 01:21:00 +00003200 }
Daniel Dunbar65229332009-03-13 11:38:42 +00003201 case phases::Compile: {
David Blaikie486f4402014-08-29 07:25:23 +00003202 if (Args.hasArg(options::OPT_fsyntax_only))
Justin Lebar41094612016-01-11 23:07:27 +00003203 return C.MakeAction<CompileJobAction>(Input, types::TY_Nothing);
David Blaikie486f4402014-08-29 07:25:23 +00003204 if (Args.hasArg(options::OPT_rewrite_objc))
Justin Lebar41094612016-01-11 23:07:27 +00003205 return C.MakeAction<CompileJobAction>(Input, types::TY_RewrittenObjC);
David Blaikie486f4402014-08-29 07:25:23 +00003206 if (Args.hasArg(options::OPT_rewrite_legacy_objc))
Justin Lebar41094612016-01-11 23:07:27 +00003207 return C.MakeAction<CompileJobAction>(Input,
3208 types::TY_RewrittenLegacyObjC);
David Blaikie486f4402014-08-29 07:25:23 +00003209 if (Args.hasArg(options::OPT__analyze, options::OPT__analyze_auto))
Justin Lebar41094612016-01-11 23:07:27 +00003210 return C.MakeAction<AnalyzeJobAction>(Input, types::TY_Plist);
David Blaikie486f4402014-08-29 07:25:23 +00003211 if (Args.hasArg(options::OPT__migrate))
Justin Lebar41094612016-01-11 23:07:27 +00003212 return C.MakeAction<MigrateJobAction>(Input, types::TY_Remap);
David Blaikie486f4402014-08-29 07:25:23 +00003213 if (Args.hasArg(options::OPT_emit_ast))
Justin Lebar41094612016-01-11 23:07:27 +00003214 return C.MakeAction<CompileJobAction>(Input, types::TY_AST);
David Blaikie486f4402014-08-29 07:25:23 +00003215 if (Args.hasArg(options::OPT_module_file_info))
Justin Lebar41094612016-01-11 23:07:27 +00003216 return C.MakeAction<CompileJobAction>(Input, types::TY_ModuleFile);
David Blaikie486f4402014-08-29 07:25:23 +00003217 if (Args.hasArg(options::OPT_verify_pch))
Justin Lebar41094612016-01-11 23:07:27 +00003218 return C.MakeAction<VerifyPCHJobAction>(Input, types::TY_Nothing);
3219 return C.MakeAction<CompileJobAction>(Input, types::TY_LLVM_BC);
Bob Wilson23a55f12014-12-21 07:00:00 +00003220 }
3221 case phases::Backend: {
Artem Belevichecb178b2018-03-21 22:22:59 +00003222 if (isUsingLTO() && TargetDeviceOffloadKind == Action::OFK_None) {
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00003223 types::ID Output =
Douglas Katzmana67e50c2015-06-26 15:47:46 +00003224 Args.hasArg(options::OPT_S) ? types::TY_LTO_IR : types::TY_LTO_BC;
Justin Lebar41094612016-01-11 23:07:27 +00003225 return C.MakeAction<BackendJobAction>(Input, Output);
David Blaikie486f4402014-08-29 07:25:23 +00003226 }
3227 if (Args.hasArg(options::OPT_emit_llvm)) {
Shuxin Yang4b3c7ff2013-08-23 21:34:57 +00003228 types::ID Output =
Douglas Katzmana67e50c2015-06-26 15:47:46 +00003229 Args.hasArg(options::OPT_S) ? types::TY_LLVM_IR : types::TY_LLVM_BC;
Justin Lebar41094612016-01-11 23:07:27 +00003230 return C.MakeAction<BackendJobAction>(Input, Output);
Daniel Dunbar65229332009-03-13 11:38:42 +00003231 }
Justin Lebar41094612016-01-11 23:07:27 +00003232 return C.MakeAction<BackendJobAction>(Input, types::TY_PP_Asm);
Daniel Dunbar65229332009-03-13 11:38:42 +00003233 }
3234 case phases::Assemble:
Justin Lebar21e5d4f2016-01-14 21:41:27 +00003235 return C.MakeAction<AssembleJobAction>(std::move(Input), types::TY_Object);
Daniel Dunbar65229332009-03-13 11:38:42 +00003236 }
3237
David Blaikie83d382b2011-09-23 05:06:16 +00003238 llvm_unreachable("invalid phase in ConstructPhaseAction");
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00003239}
3240
Daniel Dunbarf0eddb82009-03-18 02:55:38 +00003241void Driver::BuildJobs(Compilation &C) const {
Daniel Dunbar2608c542009-03-18 01:38:48 +00003242 llvm::PrettyStackTraceString CrashInfo("Building compilation jobs");
Daniel Dunbare75d8342009-03-16 06:56:51 +00003243
3244 Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o);
3245
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00003246 // It is an error to provide a -o option if we are making multiple output
3247 // files.
Daniel Dunbare75d8342009-03-16 06:56:51 +00003248 if (FinalOutput) {
3249 unsigned NumOutputs = 0;
Saleem Abdulrasoolda3f4e52014-12-29 21:02:47 +00003250 for (const Action *A : C.getActions())
3251 if (A->getType() != types::TY_Nothing)
Daniel Dunbare75d8342009-03-16 06:56:51 +00003252 ++NumOutputs;
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00003253
Daniel Dunbare75d8342009-03-16 06:56:51 +00003254 if (NumOutputs > 1) {
3255 Diag(clang::diag::err_drv_output_argument_with_multiple_files);
Craig Topper92fc2df2014-05-17 16:56:41 +00003256 FinalOutput = nullptr;
Daniel Dunbare75d8342009-03-16 06:56:51 +00003257 }
3258 }
3259
Chad Rosier35767232013-04-30 22:01:21 +00003260 // Collect the list of architectures.
3261 llvm::StringSet<> ArchNames;
Saleem Abdulrasool688b6bc2014-12-29 19:01:36 +00003262 if (C.getDefaultToolChain().getTriple().isOSBinFormatMachO())
3263 for (const Arg *A : C.getArgs())
Chad Rosier35767232013-04-30 22:01:21 +00003264 if (A->getOption().matches(options::OPT_arch))
3265 ArchNames.insert(A->getValue());
Chad Rosier35767232013-04-30 22:01:21 +00003266
Justin Lebarb44f6fe2016-01-14 21:41:21 +00003267 // Set of (Action, canonical ToolChain triple) pairs we've built jobs for.
3268 std::map<std::pair<const Action *, std::string>, InputInfo> CachedResults;
Saleem Abdulrasool688b6bc2014-12-29 19:01:36 +00003269 for (Action *A : C.getActions()) {
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00003270 // If we are linking an image for multiple archs then the linker wants
3271 // -arch_multiple and -final_output <final image name>. Unfortunately, this
3272 // doesn't fit in cleanly because we have to pass this information down.
Daniel Dunbare75d8342009-03-16 06:56:51 +00003273 //
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00003274 // FIXME: This is a hack; find a cleaner way to integrate this into the
3275 // process.
Craig Topper92fc2df2014-05-17 16:56:41 +00003276 const char *LinkingOutput = nullptr;
Daniel Dunbardd765242009-03-26 16:12:09 +00003277 if (isa<LipoJobAction>(A)) {
Daniel Dunbare75d8342009-03-16 06:56:51 +00003278 if (FinalOutput)
Richard Smithbd55daf2012-11-01 04:30:05 +00003279 LinkingOutput = FinalOutput->getValue();
Daniel Dunbare75d8342009-03-16 06:56:51 +00003280 else
Hans Wennborga7707222015-01-09 17:38:53 +00003281 LinkingOutput = getDefaultImageName();
Daniel Dunbare75d8342009-03-16 06:56:51 +00003282 }
3283
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00003284 BuildJobsForAction(C, A, &C.getDefaultToolChain(),
Mehdi Aminic50b1a22016-10-07 21:27:26 +00003285 /*BoundArch*/ StringRef(),
Daniel Dunbare75d8342009-03-16 06:56:51 +00003286 /*AtTopLevel*/ true,
Chad Rosier35767232013-04-30 22:01:21 +00003287 /*MultipleArchs*/ ArchNames.size() > 1,
Samuel Antaod06239d2016-07-15 23:13:27 +00003288 /*LinkingOutput*/ LinkingOutput, CachedResults,
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003289 /*TargetDeviceOffloadKind*/ Action::OFK_None);
Daniel Dunbare75d8342009-03-16 06:56:51 +00003290 }
Daniel Dunbar3ce436d2009-03-16 06:42:30 +00003291
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00003292 // If the user passed -Qunused-arguments or there were errors, don't warn
3293 // about any unused arguments.
Argyrios Kyrtzidis31448a42010-11-18 21:47:07 +00003294 if (Diags.hasErrorOccurred() ||
Daniel Dunbara3cfbe32009-04-07 19:04:18 +00003295 C.getArgs().hasArg(options::OPT_Qunused_arguments))
Daniel Dunbard175d972009-03-18 18:03:46 +00003296 return;
3297
Daniel Dunbar58399ae2009-03-29 22:24:54 +00003298 // Claim -### here.
Douglas Katzmana67e50c2015-06-26 15:47:46 +00003299 (void)C.getArgs().hasArg(options::OPT__HASH_HASH_HASH);
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00003300
Nico Weber47bf5052016-04-25 21:15:49 +00003301 // Claim --driver-mode, --rsp-quoting, it was handled earlier.
Douglas Katzmana67e50c2015-06-26 15:47:46 +00003302 (void)C.getArgs().hasArg(options::OPT_driver_mode);
Nico Weber47bf5052016-04-25 21:15:49 +00003303 (void)C.getArgs().hasArg(options::OPT_rsp_quoting);
Hans Wennborg70850d82013-07-18 20:29:38 +00003304
Saleem Abdulrasool688b6bc2014-12-29 19:01:36 +00003305 for (Arg *A : C.getArgs()) {
Daniel Dunbar3ce436d2009-03-16 06:42:30 +00003306 // FIXME: It would be nice to be able to send the argument to the
David Blaikie9c902b52011-09-25 23:23:43 +00003307 // DiagnosticsEngine, so that extra values, position, and so on could be
3308 // printed.
Daniel Dunbar90dd6f42009-04-04 00:52:26 +00003309 if (!A->isClaimed()) {
Michael J. Spencer66e2b202012-10-19 22:37:06 +00003310 if (A->getOption().hasFlag(options::NoArgumentUnused))
Daniel Dunbara3cfbe32009-04-07 19:04:18 +00003311 continue;
3312
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00003313 // Suppress the warning automatically if this is just a flag, and it is an
3314 // instance of an argument we already claimed.
Daniel Dunbar90dd6f42009-04-04 00:52:26 +00003315 const Option &Opt = A->getOption();
Michael J. Spencerad3ccc32012-08-20 21:41:17 +00003316 if (Opt.getKind() == Option::FlagClass) {
Daniel Dunbar90dd6f42009-04-04 00:52:26 +00003317 bool DuplicateClaimed = false;
3318
Sean Silva14facf32015-06-09 01:57:17 +00003319 for (const Arg *AA : C.getArgs().filtered(&Opt)) {
3320 if (AA->isClaimed()) {
Daniel Dunbar90dd6f42009-04-04 00:52:26 +00003321 DuplicateClaimed = true;
3322 break;
3323 }
3324 }
3325
3326 if (DuplicateClaimed)
3327 continue;
3328 }
3329
Ehsan Akhgarid8518332016-01-25 21:14:52 +00003330 // In clang-cl, don't mention unknown arguments here since they have
3331 // already been warned about.
3332 if (!IsCLMode() || !A->getOption().matches(options::OPT_UNKNOWN))
3333 Diag(clang::diag::warn_drv_unused_argument)
3334 << A->getAsString(C.getArgs());
Daniel Dunbar90dd6f42009-04-04 00:52:26 +00003335 }
Daniel Dunbar3ce436d2009-03-16 06:42:30 +00003336 }
Daniel Dunbar95e6b192009-03-13 22:12:33 +00003337}
Daniel Dunbarc4343942010-02-03 03:07:56 +00003338
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00003339namespace {
3340/// Utility class to control the collapse of dependent actions and select the
3341/// tools accordingly.
3342class ToolSelector final {
3343 /// The tool chain this selector refers to.
3344 const ToolChain &TC;
Daniel Dunbarf9ff3502010-05-14 02:03:00 +00003345
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00003346 /// The compilation this selector refers to.
3347 const Compilation &C;
Samuel Antaod06239d2016-07-15 23:13:27 +00003348
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00003349 /// The base action this selector refers to.
3350 const JobAction *BaseAction;
Samuel Antaod06239d2016-07-15 23:13:27 +00003351
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00003352 /// Set to true if the current toolchain refers to host actions.
3353 bool IsHostSelector;
Samuel Antaod06239d2016-07-15 23:13:27 +00003354
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00003355 /// Set to true if save-temps and embed-bitcode functionalities are active.
3356 bool SaveTemps;
3357 bool EmbedBitcode;
3358
3359 /// Get previous dependent action or null if that does not exist. If
3360 /// \a CanBeCollapsed is false, that action must be legal to collapse or
3361 /// null will be returned.
3362 const JobAction *getPrevDependentAction(const ActionList &Inputs,
3363 ActionList &SavedOffloadAction,
3364 bool CanBeCollapsed = true) {
3365 // An option can be collapsed only if it has a single input.
3366 if (Inputs.size() != 1)
Craig Topper92fc2df2014-05-17 16:56:41 +00003367 return nullptr;
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00003368
3369 Action *CurAction = *Inputs.begin();
3370 if (CanBeCollapsed &&
3371 !CurAction->isCollapsingWithNextDependentActionLegal())
3372 return nullptr;
3373
3374 // If the input action is an offload action. Look through it and save any
3375 // offload action that can be dropped in the event of a collapse.
3376 if (auto *OA = dyn_cast<OffloadAction>(CurAction)) {
3377 // If the dependent action is a device action, we will attempt to collapse
3378 // only with other device actions. Otherwise, we would do the same but
3379 // with host actions only.
3380 if (!IsHostSelector) {
3381 if (OA->hasSingleDeviceDependence(/*DoNotConsiderHostActions=*/true)) {
3382 CurAction =
3383 OA->getSingleDeviceDependence(/*DoNotConsiderHostActions=*/true);
3384 if (CanBeCollapsed &&
3385 !CurAction->isCollapsingWithNextDependentActionLegal())
3386 return nullptr;
3387 SavedOffloadAction.push_back(OA);
3388 return dyn_cast<JobAction>(CurAction);
3389 }
3390 } else if (OA->hasHostDependence()) {
3391 CurAction = OA->getHostDependence();
3392 if (CanBeCollapsed &&
3393 !CurAction->isCollapsingWithNextDependentActionLegal())
3394 return nullptr;
3395 SavedOffloadAction.push_back(OA);
3396 return dyn_cast<JobAction>(CurAction);
3397 }
3398 return nullptr;
3399 }
3400
3401 return dyn_cast<JobAction>(CurAction);
3402 }
3403
3404 /// Return true if an assemble action can be collapsed.
3405 bool canCollapseAssembleAction() const {
3406 return TC.useIntegratedAs() && !SaveTemps &&
3407 !C.getArgs().hasArg(options::OPT_via_file_asm) &&
3408 !C.getArgs().hasArg(options::OPT__SLASH_FA) &&
3409 !C.getArgs().hasArg(options::OPT__SLASH_Fa);
3410 }
3411
3412 /// Return true if a preprocessor action can be collapsed.
3413 bool canCollapsePreprocessorAction() const {
3414 return !C.getArgs().hasArg(options::OPT_no_integrated_cpp) &&
3415 !C.getArgs().hasArg(options::OPT_traditional_cpp) && !SaveTemps &&
3416 !C.getArgs().hasArg(options::OPT_rewrite_objc);
3417 }
3418
3419 /// Struct that relates an action with the offload actions that would be
3420 /// collapsed with it.
3421 struct JobActionInfo final {
3422 /// The action this info refers to.
3423 const JobAction *JA = nullptr;
3424 /// The offload actions we need to take care off if this action is
3425 /// collapsed.
3426 ActionList SavedOffloadAction;
3427 };
3428
3429 /// Append collapsed offload actions from the give nnumber of elements in the
3430 /// action info array.
3431 static void AppendCollapsedOffloadAction(ActionList &CollapsedOffloadAction,
3432 ArrayRef<JobActionInfo> &ActionInfo,
3433 unsigned ElementNum) {
3434 assert(ElementNum <= ActionInfo.size() && "Invalid number of elements.");
3435 for (unsigned I = 0; I < ElementNum; ++I)
3436 CollapsedOffloadAction.append(ActionInfo[I].SavedOffloadAction.begin(),
3437 ActionInfo[I].SavedOffloadAction.end());
3438 }
3439
3440 /// Functions that attempt to perform the combining. They detect if that is
3441 /// legal, and if so they update the inputs \a Inputs and the offload action
3442 /// that were collapsed in \a CollapsedOffloadAction. A tool that deals with
3443 /// the combined action is returned. If the combining is not legal or if the
3444 /// tool does not exist, null is returned.
3445 /// Currently three kinds of collapsing are supported:
3446 /// - Assemble + Backend + Compile;
3447 /// - Assemble + Backend ;
3448 /// - Backend + Compile.
3449 const Tool *
3450 combineAssembleBackendCompile(ArrayRef<JobActionInfo> ActionInfo,
3451 const ActionList *&Inputs,
3452 ActionList &CollapsedOffloadAction) {
3453 if (ActionInfo.size() < 3 || !canCollapseAssembleAction())
3454 return nullptr;
3455 auto *AJ = dyn_cast<AssembleJobAction>(ActionInfo[0].JA);
3456 auto *BJ = dyn_cast<BackendJobAction>(ActionInfo[1].JA);
3457 auto *CJ = dyn_cast<CompileJobAction>(ActionInfo[2].JA);
3458 if (!AJ || !BJ || !CJ)
3459 return nullptr;
3460
3461 // Get compiler tool.
3462 const Tool *T = TC.SelectTool(*CJ);
3463 if (!T)
3464 return nullptr;
3465
Steven Wu574b0f22016-03-01 01:07:58 +00003466 // When using -fembed-bitcode, it is required to have the same tool (clang)
3467 // for both CompilerJA and BackendJA. Otherwise, combine two stages.
3468 if (EmbedBitcode) {
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00003469 const Tool *BT = TC.SelectTool(*BJ);
3470 if (BT == T)
3471 return nullptr;
Steven Wu574b0f22016-03-01 01:07:58 +00003472 }
Bob Wilson23a55f12014-12-21 07:00:00 +00003473
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00003474 if (!T->hasIntegratedAssembler())
Bob Wilson23a55f12014-12-21 07:00:00 +00003475 return nullptr;
Samuel Antaod06239d2016-07-15 23:13:27 +00003476
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00003477 Inputs = &CJ->getInputs();
3478 AppendCollapsedOffloadAction(CollapsedOffloadAction, ActionInfo,
3479 /*NumElements=*/3);
3480 return T;
3481 }
3482 const Tool *combineAssembleBackend(ArrayRef<JobActionInfo> ActionInfo,
3483 const ActionList *&Inputs,
3484 ActionList &CollapsedOffloadAction) {
3485 if (ActionInfo.size() < 2 || !canCollapseAssembleAction())
3486 return nullptr;
3487 auto *AJ = dyn_cast<AssembleJobAction>(ActionInfo[0].JA);
3488 auto *BJ = dyn_cast<BackendJobAction>(ActionInfo[1].JA);
3489 if (!AJ || !BJ)
3490 return nullptr;
3491
3492 // Retrieve the compile job, backend action must always be preceded by one.
3493 ActionList CompileJobOffloadActions;
3494 auto *CJ = getPrevDependentAction(BJ->getInputs(), CompileJobOffloadActions,
3495 /*CanBeCollapsed=*/false);
3496 if (!AJ || !BJ || !CJ)
3497 return nullptr;
3498
3499 assert(isa<CompileJobAction>(CJ) &&
3500 "Expecting compile job preceding backend job.");
3501
3502 // Get compiler tool.
3503 const Tool *T = TC.SelectTool(*CJ);
3504 if (!T)
3505 return nullptr;
3506
3507 if (!T->hasIntegratedAssembler())
3508 return nullptr;
3509
3510 Inputs = &BJ->getInputs();
3511 AppendCollapsedOffloadAction(CollapsedOffloadAction, ActionInfo,
3512 /*NumElements=*/2);
3513 return T;
3514 }
3515 const Tool *combineBackendCompile(ArrayRef<JobActionInfo> ActionInfo,
3516 const ActionList *&Inputs,
3517 ActionList &CollapsedOffloadAction) {
Teresa Johnson9e4321c2018-04-17 16:39:25 +00003518 if (ActionInfo.size() < 2)
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00003519 return nullptr;
3520 auto *BJ = dyn_cast<BackendJobAction>(ActionInfo[0].JA);
3521 auto *CJ = dyn_cast<CompileJobAction>(ActionInfo[1].JA);
3522 if (!BJ || !CJ)
3523 return nullptr;
3524
Teresa Johnson9e4321c2018-04-17 16:39:25 +00003525 // Check if the initial input (to the compile job or its predessor if one
3526 // exists) is LLVM bitcode. In that case, no preprocessor step is required
3527 // and we can still collapse the compile and backend jobs when we have
3528 // -save-temps. I.e. there is no need for a separate compile job just to
3529 // emit unoptimized bitcode.
3530 bool InputIsBitcode = true;
3531 for (size_t i = 1; i < ActionInfo.size(); i++)
3532 if (ActionInfo[i].JA->getType() != types::TY_LLVM_BC &&
3533 ActionInfo[i].JA->getType() != types::TY_LTO_BC) {
3534 InputIsBitcode = false;
3535 break;
3536 }
3537 if (!InputIsBitcode && !canCollapsePreprocessorAction())
3538 return nullptr;
3539
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00003540 // Get compiler tool.
3541 const Tool *T = TC.SelectTool(*CJ);
3542 if (!T)
3543 return nullptr;
3544
Teresa Johnson9e4321c2018-04-17 16:39:25 +00003545 if (T->canEmitIR() && ((SaveTemps && !InputIsBitcode) || EmbedBitcode))
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00003546 return nullptr;
3547
3548 Inputs = &CJ->getInputs();
3549 AppendCollapsedOffloadAction(CollapsedOffloadAction, ActionInfo,
3550 /*NumElements=*/2);
3551 return T;
3552 }
3553
3554 /// Updates the inputs if the obtained tool supports combining with
3555 /// preprocessor action, and the current input is indeed a preprocessor
3556 /// action. If combining results in the collapse of offloading actions, those
3557 /// are appended to \a CollapsedOffloadAction.
3558 void combineWithPreprocessor(const Tool *T, const ActionList *&Inputs,
3559 ActionList &CollapsedOffloadAction) {
3560 if (!T || !canCollapsePreprocessorAction() || !T->hasIntegratedCPP())
3561 return;
3562
3563 // Attempt to get a preprocessor action dependence.
3564 ActionList PreprocessJobOffloadActions;
3565 auto *PJ = getPrevDependentAction(*Inputs, PreprocessJobOffloadActions);
3566 if (!PJ || !isa<PreprocessJobAction>(PJ))
3567 return;
3568
3569 // This is legal to combine. Append any offload action we found and set the
3570 // current inputs to preprocessor inputs.
3571 CollapsedOffloadAction.append(PreprocessJobOffloadActions.begin(),
3572 PreprocessJobOffloadActions.end());
3573 Inputs = &PJ->getInputs();
3574 }
3575
3576public:
3577 ToolSelector(const JobAction *BaseAction, const ToolChain &TC,
3578 const Compilation &C, bool SaveTemps, bool EmbedBitcode)
3579 : TC(TC), C(C), BaseAction(BaseAction), SaveTemps(SaveTemps),
3580 EmbedBitcode(EmbedBitcode) {
3581 assert(BaseAction && "Invalid base action.");
3582 IsHostSelector = BaseAction->getOffloadingDeviceKind() == Action::OFK_None;
3583 }
3584
3585 /// Check if a chain of actions can be combined and return the tool that can
3586 /// handle the combination of actions. The pointer to the current inputs \a
3587 /// Inputs and the list of offload actions \a CollapsedOffloadActions
3588 /// connected to collapsed actions are updated accordingly. The latter enables
3589 /// the caller of the selector to process them afterwards instead of just
3590 /// dropping them. If no suitable tool is found, null will be returned.
3591 const Tool *getTool(const ActionList *&Inputs,
3592 ActionList &CollapsedOffloadAction) {
3593 //
3594 // Get the largest chain of actions that we could combine.
3595 //
3596
3597 SmallVector<JobActionInfo, 5> ActionChain(1);
3598 ActionChain.back().JA = BaseAction;
3599 while (ActionChain.back().JA) {
3600 const Action *CurAction = ActionChain.back().JA;
3601
3602 // Grow the chain by one element.
3603 ActionChain.resize(ActionChain.size() + 1);
3604 JobActionInfo &AI = ActionChain.back();
3605
3606 // Attempt to fill it with the
3607 AI.JA =
3608 getPrevDependentAction(CurAction->getInputs(), AI.SavedOffloadAction);
Daniel Dunbarc4343942010-02-03 03:07:56 +00003609 }
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00003610
3611 // Pop the last action info as it could not be filled.
3612 ActionChain.pop_back();
3613
3614 //
3615 // Attempt to combine actions. If all combining attempts failed, just return
3616 // the tool of the provided action. At the end we attempt to combine the
3617 // action with any preprocessor action it may depend on.
3618 //
3619
3620 const Tool *T = combineAssembleBackendCompile(ActionChain, Inputs,
3621 CollapsedOffloadAction);
3622 if (!T)
3623 T = combineAssembleBackend(ActionChain, Inputs, CollapsedOffloadAction);
3624 if (!T)
3625 T = combineBackendCompile(ActionChain, Inputs, CollapsedOffloadAction);
3626 if (!T) {
3627 Inputs = &BaseAction->getInputs();
3628 T = TC.SelectTool(*BaseAction);
3629 }
3630
3631 combineWithPreprocessor(T, Inputs, CollapsedOffloadAction);
3632 return T;
Daniel Dunbarc4343942010-02-03 03:07:56 +00003633 }
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00003634};
Daniel Dunbarc4343942010-02-03 03:07:56 +00003635}
3636
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003637/// Return a string that uniquely identifies the result of a job. The bound arch
3638/// is not necessarily represented in the toolchain's triple -- for example,
3639/// armv7 and armv7s both map to the same triple -- so we need both in our map.
3640/// Also, we need to add the offloading device kind, as the same tool chain can
3641/// be used for host and device for some programming models, e.g. OpenMP.
3642static std::string GetTriplePlusArchString(const ToolChain *TC,
3643 StringRef BoundArch,
3644 Action::OffloadKind OffloadKind) {
Justin Lebar55c83322016-01-16 03:30:08 +00003645 std::string TriplePlusArch = TC->getTriple().normalize();
Mehdi Aminic50b1a22016-10-07 21:27:26 +00003646 if (!BoundArch.empty()) {
Justin Lebar55c83322016-01-16 03:30:08 +00003647 TriplePlusArch += "-";
3648 TriplePlusArch += BoundArch;
3649 }
Samuel Antao59efaed2016-10-27 17:31:22 +00003650 TriplePlusArch += "-";
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003651 TriplePlusArch += Action::GetOffloadKindName(OffloadKind);
3652 return TriplePlusArch;
3653}
3654
3655InputInfo Driver::BuildJobsForAction(
3656 Compilation &C, const Action *A, const ToolChain *TC, StringRef BoundArch,
3657 bool AtTopLevel, bool MultipleArchs, const char *LinkingOutput,
3658 std::map<std::pair<const Action *, std::string>, InputInfo> &CachedResults,
3659 Action::OffloadKind TargetDeviceOffloadKind) const {
3660 std::pair<const Action *, std::string> ActionTC = {
3661 A, GetTriplePlusArchString(TC, BoundArch, TargetDeviceOffloadKind)};
Justin Lebarb44f6fe2016-01-14 21:41:21 +00003662 auto CachedResult = CachedResults.find(ActionTC);
3663 if (CachedResult != CachedResults.end()) {
3664 return CachedResult->second;
3665 }
Samuel Antaod06239d2016-07-15 23:13:27 +00003666 InputInfo Result = BuildJobsForActionNoCache(
3667 C, A, TC, BoundArch, AtTopLevel, MultipleArchs, LinkingOutput,
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003668 CachedResults, TargetDeviceOffloadKind);
Justin Lebarb44f6fe2016-01-14 21:41:21 +00003669 CachedResults[ActionTC] = Result;
3670 return Result;
3671}
3672
3673InputInfo Driver::BuildJobsForActionNoCache(
Mehdi Aminic50b1a22016-10-07 21:27:26 +00003674 Compilation &C, const Action *A, const ToolChain *TC, StringRef BoundArch,
Justin Lebarb44f6fe2016-01-14 21:41:21 +00003675 bool AtTopLevel, bool MultipleArchs, const char *LinkingOutput,
Samuel Antaod06239d2016-07-15 23:13:27 +00003676 std::map<std::pair<const Action *, std::string>, InputInfo> &CachedResults,
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003677 Action::OffloadKind TargetDeviceOffloadKind) const {
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00003678 llvm::PrettyStackTraceString CrashInfo("Building compilation jobs");
Daniel Dunbarc4acf9d2009-03-18 23:18:19 +00003679
Samuel Antaod06239d2016-07-15 23:13:27 +00003680 InputInfoList OffloadDependencesInputInfo;
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003681 bool BuildingForOffloadDevice = TargetDeviceOffloadKind != Action::OFK_None;
Samuel Antaod06239d2016-07-15 23:13:27 +00003682 if (const OffloadAction *OA = dyn_cast<OffloadAction>(A)) {
Alex Lorenz4003a982017-08-08 11:22:21 +00003683 // The 'Darwin' toolchain is initialized only when its arguments are
3684 // computed. Get the default arguments for OFK_None to ensure that
3685 // initialization is performed before processing the offload action.
3686 // FIXME: Remove when darwin's toolchain is initialized during construction.
3687 C.getArgsForToolChain(TC, BoundArch, Action::OFK_None);
3688
Samuel Antaod06239d2016-07-15 23:13:27 +00003689 // The offload action is expected to be used in four different situations.
3690 //
3691 // a) Set a toolchain/architecture/kind for a host action:
3692 // Host Action 1 -> OffloadAction -> Host Action 2
3693 //
3694 // b) Set a toolchain/architecture/kind for a device action;
3695 // Device Action 1 -> OffloadAction -> Device Action 2
3696 //
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00003697 // c) Specify a device dependence to a host action;
Samuel Antaod06239d2016-07-15 23:13:27 +00003698 // Device Action 1 _
3699 // \
3700 // Host Action 1 ---> OffloadAction -> Host Action 2
3701 //
3702 // d) Specify a host dependence to a device action.
3703 // Host Action 1 _
3704 // \
3705 // Device Action 1 ---> OffloadAction -> Device Action 2
3706 //
3707 // For a) and b), we just return the job generated for the dependence. For
3708 // c) and d) we override the current action with the host/device dependence
3709 // if the current toolchain is host/device and set the offload dependences
3710 // info with the jobs obtained from the device/host dependence(s).
3711
3712 // If there is a single device option, just generate the job for it.
3713 if (OA->hasSingleDeviceDependence()) {
3714 InputInfo DevA;
3715 OA->doOnEachDeviceDependence([&](Action *DepA, const ToolChain *DepTC,
3716 const char *DepBoundArch) {
3717 DevA =
3718 BuildJobsForAction(C, DepA, DepTC, DepBoundArch, AtTopLevel,
3719 /*MultipleArchs*/ !!DepBoundArch, LinkingOutput,
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003720 CachedResults, DepA->getOffloadingDeviceKind());
Samuel Antaod06239d2016-07-15 23:13:27 +00003721 });
3722 return DevA;
Artem Belevich0ff05cd2015-07-13 23:27:56 +00003723 }
Samuel Antaod06239d2016-07-15 23:13:27 +00003724
3725 // If 'Action 2' is host, we generate jobs for the device dependences and
3726 // override the current action with the host dependence. Otherwise, we
3727 // generate the host dependences and override the action with the device
3728 // dependence. The dependences can't therefore be a top-level action.
3729 OA->doOnEachDependence(
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003730 /*IsHostDependence=*/BuildingForOffloadDevice,
Samuel Antaod06239d2016-07-15 23:13:27 +00003731 [&](Action *DepA, const ToolChain *DepTC, const char *DepBoundArch) {
3732 OffloadDependencesInputInfo.push_back(BuildJobsForAction(
3733 C, DepA, DepTC, DepBoundArch, /*AtTopLevel=*/false,
3734 /*MultipleArchs*/ !!DepBoundArch, LinkingOutput, CachedResults,
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003735 DepA->getOffloadingDeviceKind()));
Samuel Antaod06239d2016-07-15 23:13:27 +00003736 });
3737
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003738 A = BuildingForOffloadDevice
Samuel Antaod06239d2016-07-15 23:13:27 +00003739 ? OA->getSingleDeviceDependence(/*DoNotConsiderHostActions=*/true)
3740 : OA->getHostDependence();
Artem Belevich0ff05cd2015-07-13 23:27:56 +00003741 }
3742
Daniel Dunbare75d8342009-03-16 06:56:51 +00003743 if (const InputAction *IA = dyn_cast<InputAction>(A)) {
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00003744 // FIXME: It would be nice to not claim this here; maybe the old scheme of
3745 // just using Args was better?
Daniel Dunbar5cdf3e02009-03-19 07:29:38 +00003746 const Arg &Input = IA->getInputArg();
3747 Input.claim();
Daniel Dunbar35cbfeb2010-06-09 22:31:08 +00003748 if (Input.getOption().matches(options::OPT_INPUT)) {
Richard Smithbd55daf2012-11-01 04:30:05 +00003749 const char *Name = Input.getValue();
Justin Lebard98cea82016-01-11 23:15:21 +00003750 return InputInfo(A, Name, /* BaseInput = */ Name);
Douglas Katzman678d0cb2015-06-16 18:01:24 +00003751 }
Justin Lebard98cea82016-01-11 23:15:21 +00003752 return InputInfo(A, &Input, /* BaseInput = */ "");
Daniel Dunbare75d8342009-03-16 06:56:51 +00003753 }
3754
3755 if (const BindArchAction *BAA = dyn_cast<BindArchAction>(A)) {
Chad Rosiera78a6eb2012-04-27 16:50:38 +00003756 const ToolChain *TC;
Mehdi Aminic50b1a22016-10-07 21:27:26 +00003757 StringRef ArchName = BAA->getArchName();
Daniel Dunbar1ef3f2a2009-09-08 23:37:19 +00003758
Mehdi Aminic50b1a22016-10-07 21:27:26 +00003759 if (!ArchName.empty())
Andrey Turetskiy6a8b91d2016-04-21 10:16:48 +00003760 TC = &getToolChain(C.getArgs(),
Petr Hosekdd38d932018-05-29 22:35:39 +00003761 computeTargetTriple(*this, TargetTriple,
Andrey Turetskiy6a8b91d2016-04-21 10:16:48 +00003762 C.getArgs(), ArchName));
Chad Rosiera78a6eb2012-04-27 16:50:38 +00003763 else
3764 TC = &C.getDefaultToolChain();
Daniel Dunbar1ef3f2a2009-09-08 23:37:19 +00003765
Nico Weber5a459f82016-02-23 19:30:43 +00003766 return BuildJobsForAction(C, *BAA->input_begin(), TC, ArchName, AtTopLevel,
Samuel Antaod06239d2016-07-15 23:13:27 +00003767 MultipleArchs, LinkingOutput, CachedResults,
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003768 TargetDeviceOffloadKind);
Daniel Dunbare75d8342009-03-16 06:56:51 +00003769 }
3770
Artem Belevich0ff05cd2015-07-13 23:27:56 +00003771
Daniel Dunbare75d8342009-03-16 06:56:51 +00003772 const ActionList *Inputs = &A->getInputs();
Daniel Dunbarc4343942010-02-03 03:07:56 +00003773
3774 const JobAction *JA = cast<JobAction>(A);
Samuel Antaod06239d2016-07-15 23:13:27 +00003775 ActionList CollapsedOffloadActions;
3776
Mehdi Amini6683e222017-01-24 18:12:25 +00003777 ToolSelector TS(JA, *TC, C, isSaveTempsEnabled(),
3778 embedBitcodeInObject() && !isUsingLTO());
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00003779 const Tool *T = TS.getTool(Inputs, CollapsedOffloadActions);
3780
Rafael Espindola79764462013-03-24 15:06:53 +00003781 if (!T)
Justin Lebar9eaa4892016-01-11 23:09:32 +00003782 return InputInfo();
Daniel Dunbare75d8342009-03-16 06:56:51 +00003783
Samuel Antaod06239d2016-07-15 23:13:27 +00003784 // If we've collapsed action list that contained OffloadAction we
3785 // need to build jobs for host/device-side inputs it may have held.
3786 for (const auto *OA : CollapsedOffloadActions)
3787 cast<OffloadAction>(OA)->doOnEachDependence(
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003788 /*IsHostDependence=*/BuildingForOffloadDevice,
Samuel Antaod06239d2016-07-15 23:13:27 +00003789 [&](Action *DepA, const ToolChain *DepTC, const char *DepBoundArch) {
3790 OffloadDependencesInputInfo.push_back(BuildJobsForAction(
Artem Belevichbee2f412016-08-22 18:50:34 +00003791 C, DepA, DepTC, DepBoundArch, /* AtTopLevel */ false,
Samuel Antaod06239d2016-07-15 23:13:27 +00003792 /*MultipleArchs=*/!!DepBoundArch, LinkingOutput, CachedResults,
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003793 DepA->getOffloadingDeviceKind()));
Samuel Antaod06239d2016-07-15 23:13:27 +00003794 });
Artem Belevichf8144ab2015-08-27 18:10:41 +00003795
Daniel Dunbare75d8342009-03-16 06:56:51 +00003796 // Only use pipes when there is exactly one input.
Daniel Dunbar1a093d22009-03-18 06:00:36 +00003797 InputInfoList InputInfos;
Saleem Abdulrasoolda3f4e52014-12-29 21:02:47 +00003798 for (const Action *Input : *Inputs) {
Eric Christopher14668dd2013-02-18 00:38:25 +00003799 // Treat dsymutil and verify sub-jobs as being at the top-level too, they
3800 // shouldn't get temporary output names.
Daniel Dunbar6beaf512010-06-04 18:28:41 +00003801 // FIXME: Clean this up.
Justin Lebar9eaa4892016-01-11 23:09:32 +00003802 bool SubJobAtTopLevel =
3803 AtTopLevel && (isa<DsymutilJobAction>(A) || isa<VerifyJobAction>(A));
Samuel Antaod06239d2016-07-15 23:13:27 +00003804 InputInfos.push_back(BuildJobsForAction(
3805 C, Input, TC, BoundArch, SubJobAtTopLevel, MultipleArchs, LinkingOutput,
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003806 CachedResults, A->getOffloadingDeviceKind()));
Daniel Dunbare75d8342009-03-16 06:56:51 +00003807 }
3808
Daniel Dunbare75d8342009-03-16 06:56:51 +00003809 // Always use the first input as the base input.
3810 const char *BaseInput = InputInfos[0].getBaseInput();
Daniel Dunbar7a178a42009-03-17 17:53:55 +00003811
Daniel Dunbar6beaf512010-06-04 18:28:41 +00003812 // ... except dsymutil actions, which use their actual input as the base
3813 // input.
3814 if (JA->getType() == types::TY_dSYM)
3815 BaseInput = InputInfos[0].getFilename();
3816
Samuel Antaod06239d2016-07-15 23:13:27 +00003817 // Append outputs of offload device jobs to the input list
3818 if (!OffloadDependencesInputInfo.empty())
3819 InputInfos.append(OffloadDependencesInputInfo.begin(),
3820 OffloadDependencesInputInfo.end());
Artem Belevich0ff05cd2015-07-13 23:27:56 +00003821
Vedant Kumar18286cf2016-07-27 23:02:20 +00003822 // Set the effective triple of the toolchain for the duration of this job.
3823 llvm::Triple EffectiveTriple;
3824 const ToolChain &ToolTC = T->getToolChain();
Samuel Antao31fef982016-10-27 17:39:44 +00003825 const ArgList &Args =
3826 C.getArgsForToolChain(TC, BoundArch, A->getOffloadingDeviceKind());
Vedant Kumar18286cf2016-07-27 23:02:20 +00003827 if (InputInfos.size() != 1) {
3828 EffectiveTriple = llvm::Triple(ToolTC.ComputeEffectiveClangTriple(Args));
3829 } else {
3830 // Pass along the input type if it can be unambiguously determined.
3831 EffectiveTriple = llvm::Triple(
3832 ToolTC.ComputeEffectiveClangTriple(Args, InputInfos[0].getType()));
3833 }
3834 RegisterEffectiveTriple TripleRAII(ToolTC, EffectiveTriple);
3835
Daniel Dunbard00272f2010-08-02 02:38:15 +00003836 // Determine the place to write output to, if any.
Justin Lebar9eaa4892016-01-11 23:09:32 +00003837 InputInfo Result;
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003838 InputInfoList UnbundlingResults;
3839 if (auto *UA = dyn_cast<OffloadUnbundlingJobAction>(JA)) {
3840 // If we have an unbundling job, we need to create results for all the
3841 // outputs. We also update the results cache so that other actions using
3842 // this unbundling action can get the right results.
3843 for (auto &UI : UA->getDependentActionsInfo()) {
3844 assert(UI.DependentOffloadKind != Action::OFK_None &&
3845 "Unbundling with no offloading??");
3846
3847 // Unbundling actions are never at the top level. When we generate the
3848 // offloading prefix, we also do that for the host file because the
3849 // unbundling action does not change the type of the output which can
3850 // cause a overwrite.
3851 std::string OffloadingPrefix = Action::GetOffloadingFileNamePrefix(
3852 UI.DependentOffloadKind,
3853 UI.DependentToolChain->getTriple().normalize(),
3854 /*CreatePrefixForHost=*/true);
3855 auto CurI = InputInfo(
Yaxun Liu609f7522018-05-11 19:02:18 +00003856 UA,
3857 GetNamedOutputPath(C, *UA, BaseInput, UI.DependentBoundArch,
3858 /*AtTopLevel=*/false,
3859 MultipleArchs ||
3860 UI.DependentOffloadKind == Action::OFK_HIP,
3861 OffloadingPrefix),
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003862 BaseInput);
3863 // Save the unbundling result.
3864 UnbundlingResults.push_back(CurI);
3865
3866 // Get the unique string identifier for this dependence and cache the
3867 // result.
Yaxun Liu470b8332018-06-06 19:44:10 +00003868 StringRef Arch;
3869 if (TargetDeviceOffloadKind == Action::OFK_HIP) {
3870 if (UI.DependentOffloadKind == Action::OFK_Host)
3871 Arch = "all";
3872 else
3873 Arch = UI.DependentBoundArch;
3874 } else
3875 Arch = BoundArch;
3876
3877 CachedResults[{A, GetTriplePlusArchString(UI.DependentToolChain, Arch,
3878 UI.DependentOffloadKind)}] =
3879 CurI;
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003880 }
3881
3882 // Now that we have all the results generated, select the one that should be
3883 // returned for the current depending action.
3884 std::pair<const Action *, std::string> ActionTC = {
3885 A, GetTriplePlusArchString(TC, BoundArch, TargetDeviceOffloadKind)};
3886 assert(CachedResults.find(ActionTC) != CachedResults.end() &&
3887 "Result does not exist??");
3888 Result = CachedResults[ActionTC];
3889 } else if (JA->getType() == types::TY_Nothing)
Justin Lebard98cea82016-01-11 23:15:21 +00003890 Result = InputInfo(A, BaseInput);
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003891 else {
3892 // We only have to generate a prefix for the host if this is not a top-level
3893 // action.
3894 std::string OffloadingPrefix = Action::GetOffloadingFileNamePrefix(
3895 A->getOffloadingDeviceKind(), TC->getTriple().normalize(),
3896 /*CreatePrefixForHost=*/!!A->getOffloadingHostActiveKinds() &&
3897 !AtTopLevel);
Justin Lebard98cea82016-01-11 23:15:21 +00003898 Result = InputInfo(A, GetNamedOutputPath(C, *JA, BaseInput, BoundArch,
Samuel Antaod06239d2016-07-15 23:13:27 +00003899 AtTopLevel, MultipleArchs,
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003900 OffloadingPrefix),
Justin Lebard98cea82016-01-11 23:15:21 +00003901 BaseInput);
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003902 }
Daniel Dunbar7a178a42009-03-17 17:53:55 +00003903
Chad Rosierbe10f982011-08-02 17:58:04 +00003904 if (CCCPrintBindings && !CCGenDiagnostics) {
Rafael Espindola79764462013-03-24 15:06:53 +00003905 llvm::errs() << "# \"" << T->getToolChain().getTripleString() << '"'
3906 << " - \"" << T->getName() << "\", inputs: [";
Daniel Dunbarb39cc522009-03-17 22:47:06 +00003907 for (unsigned i = 0, e = InputInfos.size(); i != e; ++i) {
3908 llvm::errs() << InputInfos[i].getAsString();
3909 if (i + 1 != e)
3910 llvm::errs() << ", ";
3911 }
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003912 if (UnbundlingResults.empty())
3913 llvm::errs() << "], output: " << Result.getAsString() << "\n";
3914 else {
3915 llvm::errs() << "], outputs: [";
3916 for (unsigned i = 0, e = UnbundlingResults.size(); i != e; ++i) {
3917 llvm::errs() << UnbundlingResults[i].getAsString();
3918 if (i + 1 != e)
3919 llvm::errs() << ", ";
3920 }
3921 llvm::errs() << "] \n";
3922 }
Daniel Dunbarb39cc522009-03-17 22:47:06 +00003923 } else {
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003924 if (UnbundlingResults.empty())
3925 T->ConstructJob(
3926 C, *JA, Result, InputInfos,
3927 C.getArgsForToolChain(TC, BoundArch, JA->getOffloadingDeviceKind()),
3928 LinkingOutput);
3929 else
Samuel Antao7108bf32016-11-03 15:41:50 +00003930 T->ConstructJobMultipleOutputs(
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003931 C, *JA, UnbundlingResults, InputInfos,
3932 C.getArgsForToolChain(TC, BoundArch, JA->getOffloadingDeviceKind()),
3933 LinkingOutput);
Daniel Dunbarb39cc522009-03-17 22:47:06 +00003934 }
Justin Lebar9eaa4892016-01-11 23:09:32 +00003935 return Result;
Daniel Dunbare75d8342009-03-16 06:56:51 +00003936}
3937
Hans Wennborga7707222015-01-09 17:38:53 +00003938const char *Driver::getDefaultImageName() const {
Petr Hosekdd38d932018-05-29 22:35:39 +00003939 llvm::Triple Target(llvm::Triple::normalize(TargetTriple));
Hans Wennborga7707222015-01-09 17:38:53 +00003940 return Target.isOSWindows() ? "a.exe" : "a.out";
3941}
3942
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003943/// Create output filename based on ArgValue, which could either be a
Hans Wennborg2c21f742013-10-17 16:16:23 +00003944/// full filename, filename without extension, or a directory. If ArgValue
3945/// does not provide a filename, then use BaseName, and use the extension
3946/// suitable for FileType.
Hans Wennborg207fcf02013-08-12 21:56:42 +00003947static const char *MakeCLOutputFilename(const ArgList &Args, StringRef ArgValue,
Douglas Katzmana67e50c2015-06-26 15:47:46 +00003948 StringRef BaseName,
3949 types::ID FileType) {
Hans Wennborg207fcf02013-08-12 21:56:42 +00003950 SmallString<128> Filename = ArgValue;
Justin Bogner5aaf2e72014-06-26 20:59:36 +00003951
Hans Wennborgf1a74252013-09-10 20:18:04 +00003952 if (ArgValue.empty()) {
3953 // If the argument is empty, output to BaseName in the current dir.
3954 Filename = BaseName;
3955 } else if (llvm::sys::path::is_separator(Filename.back())) {
Hans Wennborg207fcf02013-08-12 21:56:42 +00003956 // If the argument is a directory, output to BaseName in that dir.
3957 llvm::sys::path::append(Filename, BaseName);
3958 }
3959
3960 if (!llvm::sys::path::has_extension(ArgValue)) {
3961 // If the argument didn't provide an extension, then set it.
3962 const char *Extension = types::getTypeTempSuffix(FileType, true);
Hans Wennborgf1a74252013-09-10 20:18:04 +00003963
3964 if (FileType == types::TY_Image &&
3965 Args.hasArg(options::OPT__SLASH_LD, options::OPT__SLASH_LDd)) {
3966 // The output file is a dll.
3967 Extension = "dll";
3968 }
3969
Hans Wennborg207fcf02013-08-12 21:56:42 +00003970 llvm::sys::path::replace_extension(Filename, Extension);
3971 }
3972
3973 return Args.MakeArgString(Filename.c_str());
3974}
3975
Douglas Katzmana67e50c2015-06-26 15:47:46 +00003976const char *Driver::GetNamedOutputPath(Compilation &C, const JobAction &JA,
Daniel Dunbar7a178a42009-03-17 17:53:55 +00003977 const char *BaseInput,
Mehdi Aminic50b1a22016-10-07 21:27:26 +00003978 StringRef BoundArch, bool AtTopLevel,
Samuel Antaod06239d2016-07-15 23:13:27 +00003979 bool MultipleArchs,
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003980 StringRef OffloadingPrefix) const {
Daniel Dunbar2608c542009-03-18 01:38:48 +00003981 llvm::PrettyStackTraceString CrashInfo("Computing output path");
Daniel Dunbar7a178a42009-03-17 17:53:55 +00003982 // Output to a user requested destination?
Douglas Katzmana67e50c2015-06-26 15:47:46 +00003983 if (AtTopLevel && !isa<DsymutilJobAction>(JA) && !isa<VerifyJobAction>(JA)) {
Daniel Dunbar7a178a42009-03-17 17:53:55 +00003984 if (Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o))
Chad Rosier633dcdc2013-01-24 19:14:47 +00003985 return C.addResultFile(FinalOutput->getValue(), &JA);
Daniel Dunbar7a178a42009-03-17 17:53:55 +00003986 }
3987
Hans Wennborge0053472013-12-20 18:40:46 +00003988 // For /P, preprocess to file named after BaseInput.
3989 if (C.getArgs().hasArg(options::OPT__SLASH_P)) {
3990 assert(AtTopLevel && isa<PreprocessJobAction>(JA));
3991 StringRef BaseName = llvm::sys::path::filename(BaseInput);
Hans Wennborg04c764f2014-06-17 00:19:12 +00003992 StringRef NameArg;
Greg Bedwell065f70a2015-06-09 10:24:06 +00003993 if (Arg *A = C.getArgs().getLastArg(options::OPT__SLASH_Fi))
Hans Wennborg04c764f2014-06-17 00:19:12 +00003994 NameArg = A->getValue();
Douglas Katzmana67e50c2015-06-26 15:47:46 +00003995 return C.addResultFile(
3996 MakeCLOutputFilename(C.getArgs(), NameArg, BaseName, types::TY_PP_C),
3997 &JA);
Hans Wennborge0053472013-12-20 18:40:46 +00003998 }
3999
Nick Lewycky6e1ce292010-09-24 00:46:53 +00004000 // Default to writing to stdout?
David Blaikiebc023c92018-06-14 23:09:06 +00004001 if (AtTopLevel && !CCGenDiagnostics && isa<PreprocessJobAction>(JA))
Nick Lewycky6e1ce292010-09-24 00:46:53 +00004002 return "-";
4003
Hans Wennborg2c21f742013-10-17 16:16:23 +00004004 // Is this the assembly listing for /FA?
4005 if (JA.getType() == types::TY_PP_Asm &&
4006 (C.getArgs().hasArg(options::OPT__SLASH_FA) ||
4007 C.getArgs().hasArg(options::OPT__SLASH_Fa))) {
4008 // Use /Fa and the input filename to determine the asm file name.
4009 StringRef BaseName = llvm::sys::path::filename(BaseInput);
4010 StringRef FaValue = C.getArgs().getLastArgValue(options::OPT__SLASH_Fa);
Douglas Katzmana67e50c2015-06-26 15:47:46 +00004011 return C.addResultFile(
4012 MakeCLOutputFilename(C.getArgs(), FaValue, BaseName, JA.getType()),
4013 &JA);
Hans Wennborg2c21f742013-10-17 16:16:23 +00004014 }
4015
Daniel Dunbar7a178a42009-03-17 17:53:55 +00004016 // Output to a temporary file?
Reid Kleckner68eb60b2015-02-02 22:41:48 +00004017 if ((!AtTopLevel && !isSaveTempsEnabled() &&
Douglas Katzmana67e50c2015-06-26 15:47:46 +00004018 !C.getArgs().hasArg(options::OPT__SLASH_Fo)) ||
Chad Rosierbe10f982011-08-02 17:58:04 +00004019 CCGenDiagnostics) {
Chad Rosier97c37372011-08-26 22:27:02 +00004020 StringRef Name = llvm::sys::path::filename(BaseInput);
4021 std::pair<StringRef, StringRef> Split = Name.split('.');
Bob Haarman7e4d3ff2018-07-09 21:07:20 +00004022 SmallString<128> TmpName;
4023 const char *Suffix = types::getTypeTempSuffix(JA.getType(), IsCLMode());
4024 Arg *A = C.getArgs().getLastArg(options::OPT_fcrash_diagnostics_dir);
4025 if (CCGenDiagnostics && A) {
4026 SmallString<128> CrashDirectory(A->getValue());
4027 llvm::sys::path::append(CrashDirectory, Split.first);
4028 const char *Middle = Suffix ? "-%%%%%%." : "-%%%%%%";
4029 std::error_code EC =
4030 llvm::sys::fs::createUniqueFile(CrashDirectory + Middle + Suffix, TmpName);
4031 if (EC) {
4032 Diag(clang::diag::err_unable_to_make_temp) << EC.message();
4033 return "";
4034 }
4035 } else {
4036 TmpName = GetTemporaryPath(Split.first, Suffix);
4037 }
Malcolm Parsonsf76f6502016-11-02 10:39:27 +00004038 return C.addTempFile(C.getArgs().MakeArgString(TmpName));
Daniel Dunbar7a178a42009-03-17 17:53:55 +00004039 }
4040
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00004041 SmallString<128> BasePath(BaseInput);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004042 StringRef BaseName;
Daniel Dunbar67fea712011-03-25 18:16:51 +00004043
4044 // Dsymutil actions should use the full path.
Eric Christopher551ef452011-08-23 17:56:55 +00004045 if (isa<DsymutilJobAction>(JA) || isa<VerifyJobAction>(JA))
Daniel Dunbar67fea712011-03-25 18:16:51 +00004046 BaseName = BasePath;
4047 else
4048 BaseName = llvm::sys::path::filename(BasePath);
Daniel Dunbar7a178a42009-03-17 17:53:55 +00004049
4050 // Determine what the derived output name should be.
4051 const char *NamedOutput;
Hans Wennborg2b89a262013-08-06 22:11:28 +00004052
Hans Wennborg625fba82016-10-04 21:01:04 +00004053 if ((JA.getType() == types::TY_Object || JA.getType() == types::TY_LTO_BC) &&
Ehsan Akhgari81f36b72014-09-11 18:16:21 +00004054 C.getArgs().hasArg(options::OPT__SLASH_Fo, options::OPT__SLASH_o)) {
4055 // The /Fo or /o flag decides the object filename.
Douglas Katzmana67e50c2015-06-26 15:47:46 +00004056 StringRef Val =
4057 C.getArgs()
4058 .getLastArg(options::OPT__SLASH_Fo, options::OPT__SLASH_o)
4059 ->getValue();
4060 NamedOutput =
4061 MakeCLOutputFilename(C.getArgs(), Val, BaseName, types::TY_Object);
Hans Wennborg207fcf02013-08-12 21:56:42 +00004062 } else if (JA.getType() == types::TY_Image &&
Douglas Katzmana67e50c2015-06-26 15:47:46 +00004063 C.getArgs().hasArg(options::OPT__SLASH_Fe,
4064 options::OPT__SLASH_o)) {
Ehsan Akhgari81f36b72014-09-11 18:16:21 +00004065 // The /Fe or /o flag names the linked file.
Douglas Katzmana67e50c2015-06-26 15:47:46 +00004066 StringRef Val =
4067 C.getArgs()
4068 .getLastArg(options::OPT__SLASH_Fe, options::OPT__SLASH_o)
4069 ->getValue();
4070 NamedOutput =
4071 MakeCLOutputFilename(C.getArgs(), Val, BaseName, types::TY_Image);
Hans Wennborgf1a74252013-09-10 20:18:04 +00004072 } else if (JA.getType() == types::TY_Image) {
Hans Wennborg207fcf02013-08-12 21:56:42 +00004073 if (IsCLMode()) {
4074 // clang-cl uses BaseName for the executable name.
Douglas Katzmana67e50c2015-06-26 15:47:46 +00004075 NamedOutput =
4076 MakeCLOutputFilename(C.getArgs(), "", BaseName, types::TY_Image);
Samuel Antao59efaed2016-10-27 17:31:22 +00004077 } else {
Hans Wennborga7707222015-01-09 17:38:53 +00004078 SmallString<128> Output(getDefaultImageName());
Samuel Antao3b7e38b2016-10-27 18:14:55 +00004079 Output += OffloadingPrefix;
Samuel Antao59efaed2016-10-27 17:31:22 +00004080 if (MultipleArchs && !BoundArch.empty()) {
4081 Output += "-";
4082 Output.append(BoundArch);
4083 }
Chad Rosier35767232013-04-30 22:01:21 +00004084 NamedOutput = C.getArgs().MakeArgString(Output.c_str());
Nico Weber2ca4be92016-03-01 23:16:44 +00004085 }
4086 } else if (JA.getType() == types::TY_PCH && IsCLMode()) {
Malcolm Parsonsf76f6502016-11-02 10:39:27 +00004087 NamedOutput = C.getArgs().MakeArgString(GetClPchPath(C, BaseName));
Daniel Dunbar7a178a42009-03-17 17:53:55 +00004088 } else {
Hans Wennborg0a096a02013-09-05 17:05:56 +00004089 const char *Suffix = types::getTypeTempSuffix(JA.getType(), IsCLMode());
Daniel Dunbar7a178a42009-03-17 17:53:55 +00004090 assert(Suffix && "All types used for output should have a suffix.");
4091
4092 std::string::size_type End = std::string::npos;
4093 if (!types::appendSuffixForType(JA.getType()))
4094 End = BaseName.rfind('.');
Chad Rosier35767232013-04-30 22:01:21 +00004095 SmallString<128> Suffixed(BaseName.substr(0, End));
Samuel Antao3b7e38b2016-10-27 18:14:55 +00004096 Suffixed += OffloadingPrefix;
Mehdi Aminic50b1a22016-10-07 21:27:26 +00004097 if (MultipleArchs && !BoundArch.empty()) {
Chad Rosier35767232013-04-30 22:01:21 +00004098 Suffixed += "-";
4099 Suffixed.append(BoundArch);
4100 }
Bob Wilson23a55f12014-12-21 07:00:00 +00004101 // When using both -save-temps and -emit-llvm, use a ".tmp.bc" suffix for
4102 // the unoptimized bitcode so that it does not get overwritten by the ".bc"
4103 // optimized bitcode output.
4104 if (!AtTopLevel && C.getArgs().hasArg(options::OPT_emit_llvm) &&
4105 JA.getType() == types::TY_LLVM_BC)
4106 Suffixed += ".tmp";
Daniel Dunbar7a178a42009-03-17 17:53:55 +00004107 Suffixed += '.';
4108 Suffixed += Suffix;
4109 NamedOutput = C.getArgs().MakeArgString(Suffixed.c_str());
4110 }
4111
Reid Kleckner68eb60b2015-02-02 22:41:48 +00004112 // Prepend object file path if -save-temps=obj
4113 if (!AtTopLevel && isSaveTempsObj() && C.getArgs().hasArg(options::OPT_o) &&
4114 JA.getType() != types::TY_PCH) {
4115 Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o);
4116 SmallString<128> TempPath(FinalOutput->getValue());
4117 llvm::sys::path::remove_filename(TempPath);
4118 StringRef OutputFileName = llvm::sys::path::filename(NamedOutput);
4119 llvm::sys::path::append(TempPath, OutputFileName);
4120 NamedOutput = C.getArgs().MakeArgString(TempPath.c_str());
4121 }
4122
Chad Rosier62135492012-07-09 17:31:28 +00004123 // If we're saving temps and the temp file conflicts with the input file,
Chad Rosier5b58af02012-04-20 20:05:08 +00004124 // then avoid overwriting input file.
Reid Kleckner68eb60b2015-02-02 22:41:48 +00004125 if (!AtTopLevel && isSaveTempsEnabled() && NamedOutput == BaseName) {
Chad Rosier5b58af02012-04-20 20:05:08 +00004126 bool SameFile = false;
4127 SmallString<256> Result;
4128 llvm::sys::fs::current_path(Result);
4129 llvm::sys::path::append(Result, BaseName);
4130 llvm::sys::fs::equivalent(BaseInput, Result.c_str(), SameFile);
4131 // Must share the same path to conflict.
4132 if (SameFile) {
4133 StringRef Name = llvm::sys::path::filename(BaseInput);
4134 std::pair<StringRef, StringRef> Split = Name.split('.');
Douglas Katzmana67e50c2015-06-26 15:47:46 +00004135 std::string TmpName = GetTemporaryPath(
4136 Split.first, types::getTypeTempSuffix(JA.getType(), IsCLMode()));
Malcolm Parsonsf76f6502016-11-02 10:39:27 +00004137 return C.addTempFile(C.getArgs().MakeArgString(TmpName));
Chad Rosier5b58af02012-04-20 20:05:08 +00004138 }
Chad Rosierf8412cd2011-07-15 21:54:29 +00004139 }
4140
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00004141 // As an annoying special case, PCH generation doesn't strip the pathname.
Nico Weber8ab92192016-03-02 23:29:29 +00004142 if (JA.getType() == types::TY_PCH && !IsCLMode()) {
Michael J. Spencere1696752010-12-18 00:19:12 +00004143 llvm::sys::path::remove_filename(BasePath);
4144 if (BasePath.empty())
Daniel Dunbare6c83192009-03-18 09:58:30 +00004145 BasePath = NamedOutput;
4146 else
Michael J. Spencere1696752010-12-18 00:19:12 +00004147 llvm::sys::path::append(BasePath, NamedOutput);
Chad Rosier633dcdc2013-01-24 19:14:47 +00004148 return C.addResultFile(C.getArgs().MakeArgString(BasePath.c_str()), &JA);
Daniel Dunbar7a178a42009-03-17 17:53:55 +00004149 } else {
Chad Rosier633dcdc2013-01-24 19:14:47 +00004150 return C.addResultFile(NamedOutput, &JA);
Daniel Dunbar7a178a42009-03-17 17:53:55 +00004151 }
4152}
4153
Mehdi Amini12011172016-10-06 05:11:48 +00004154std::string Driver::GetFilePath(StringRef Name, const ToolChain &TC) const {
Chandler Carruth84559242010-03-22 01:52:07 +00004155 // Respect a limited subset of the '-Bprefix' functionality in GCC by
Logan Chiencd679fd2012-10-04 08:08:56 +00004156 // attempting to use this prefix when looking for file paths.
Douglas Katzman26eabf62015-06-24 15:10:30 +00004157 for (const std::string &Dir : PrefixDirs) {
Joerg Sonnenberger6165ab12011-03-21 13:51:29 +00004158 if (Dir.empty())
4159 continue;
Douglas Katzman26eabf62015-06-24 15:10:30 +00004160 SmallString<128> P(Dir[0] == '=' ? SysRoot + Dir.substr(1) : Dir);
Rafael Espindola609a6642013-06-24 18:33:43 +00004161 llvm::sys::path::append(P, Name);
4162 if (llvm::sys::fs::exists(Twine(P)))
Chandler Carruth84559242010-03-22 01:52:07 +00004163 return P.str();
4164 }
4165
Petr Hosek916a4672017-08-10 04:16:38 +00004166 SmallString<128> R(ResourceDir);
4167 llvm::sys::path::append(R, Name);
4168 if (llvm::sys::fs::exists(Twine(R)))
4169 return R.str();
4170
4171 SmallString<128> P(TC.getCompilerRTPath());
Rafael Espindola609a6642013-06-24 18:33:43 +00004172 llvm::sys::path::append(P, Name);
4173 if (llvm::sys::fs::exists(Twine(P)))
Peter Collingbournefa9771f2011-09-06 02:08:31 +00004174 return P.str();
4175
Douglas Katzman26eabf62015-06-24 15:10:30 +00004176 for (const std::string &Dir : TC.getFilePaths()) {
Joerg Sonnenberger6165ab12011-03-21 13:51:29 +00004177 if (Dir.empty())
4178 continue;
Douglas Katzman26eabf62015-06-24 15:10:30 +00004179 SmallString<128> P(Dir[0] == '=' ? SysRoot + Dir.substr(1) : Dir);
Rafael Espindola609a6642013-06-24 18:33:43 +00004180 llvm::sys::path::append(P, Name);
4181 if (llvm::sys::fs::exists(Twine(P)))
Daniel Dunbar1ce81532009-09-09 22:33:00 +00004182 return P.str();
Daniel Dunbar68b01a02009-03-18 20:26:19 +00004183 }
4184
Daniel Dunbar1ce81532009-09-09 22:33:00 +00004185 return Name;
Daniel Dunbar5e0f6af2009-03-13 00:51:18 +00004186}
4187
Douglas Katzmana67e50c2015-06-26 15:47:46 +00004188void Driver::generatePrefixedToolNames(
Mehdi Amini12011172016-10-06 05:11:48 +00004189 StringRef Tool, const ToolChain &TC,
Douglas Katzmana67e50c2015-06-26 15:47:46 +00004190 SmallVectorImpl<std::string> &Names) const {
Petr Hosekdd38d932018-05-29 22:35:39 +00004191 // FIXME: Needs a better variable than TargetTriple
4192 Names.emplace_back((TargetTriple + "-" + Tool).str());
Benjamin Kramer3204b152015-05-29 19:42:19 +00004193 Names.emplace_back(Tool);
Vasileios Kalintirisc744e122015-11-12 15:26:54 +00004194
4195 // Allow the discovery of tools prefixed with LLVM's default target triple.
Petr Hosekdd38d932018-05-29 22:35:39 +00004196 std::string DefaultTargetTriple = llvm::sys::getDefaultTargetTriple();
4197 if (DefaultTargetTriple != TargetTriple)
4198 Names.emplace_back((DefaultTargetTriple + "-" + Tool).str());
Saleem Abdulrasoolf0ba6ce2014-10-25 23:33:21 +00004199}
4200
Benjamin Kramer7111b912014-11-04 20:26:01 +00004201static bool ScanDirForExecutable(SmallString<128> &Dir,
4202 ArrayRef<std::string> Names) {
Saleem Abdulrasoolf0ba6ce2014-10-25 23:33:21 +00004203 for (const auto &Name : Names) {
4204 llvm::sys::path::append(Dir, Name);
4205 if (llvm::sys::fs::can_execute(Twine(Dir)))
4206 return true;
4207 llvm::sys::path::remove_filename(Dir);
4208 }
4209 return false;
4210}
4211
Mehdi Amini12011172016-10-06 05:11:48 +00004212std::string Driver::GetProgramPath(StringRef Name, const ToolChain &TC) const {
Saleem Abdulrasoolf0ba6ce2014-10-25 23:33:21 +00004213 SmallVector<std::string, 2> TargetSpecificExecutables;
4214 generatePrefixedToolNames(Name, TC, TargetSpecificExecutables);
4215
Chandler Carruth84559242010-03-22 01:52:07 +00004216 // Respect a limited subset of the '-Bprefix' functionality in GCC by
Logan Chiencd679fd2012-10-04 08:08:56 +00004217 // attempting to use this prefix when looking for program paths.
Saleem Abdulrasool23d99b12014-09-16 03:48:32 +00004218 for (const auto &PrefixDir : PrefixDirs) {
4219 if (llvm::sys::fs::is_directory(PrefixDir)) {
4220 SmallString<128> P(PrefixDir);
Saleem Abdulrasoolf0ba6ce2014-10-25 23:33:21 +00004221 if (ScanDirForExecutable(P, TargetSpecificExecutables))
Rafael Espindola8be5c052013-06-19 13:24:29 +00004222 return P.str();
Simon Atanasyana47ba292012-10-31 14:39:28 +00004223 } else {
Mehdi Amini12011172016-10-06 05:11:48 +00004224 SmallString<128> P((PrefixDir + Name).str());
Rafael Espindola609a6642013-06-24 18:33:43 +00004225 if (llvm::sys::fs::can_execute(Twine(P)))
Rafael Espindola8be5c052013-06-19 13:24:29 +00004226 return P.str();
Simon Atanasyan86bdab72012-10-31 12:01:53 +00004227 }
Chandler Carruth84559242010-03-22 01:52:07 +00004228 }
4229
Daniel Dunbar68b01a02009-03-18 20:26:19 +00004230 const ToolChain::path_list &List = TC.getProgramPaths();
Saleem Abdulrasool23d99b12014-09-16 03:48:32 +00004231 for (const auto &Path : List) {
4232 SmallString<128> P(Path);
Saleem Abdulrasoolf0ba6ce2014-10-25 23:33:21 +00004233 if (ScanDirForExecutable(P, TargetSpecificExecutables))
Rafael Espindola8be5c052013-06-19 13:24:29 +00004234 return P.str();
Daniel Dunbar68b01a02009-03-18 20:26:19 +00004235 }
4236
Daniel Dunbar76ce7412009-03-23 16:15:50 +00004237 // If all else failed, search the path.
Michael J. Spencerb011d482014-11-07 21:30:32 +00004238 for (const auto &TargetSpecificExecutable : TargetSpecificExecutables)
4239 if (llvm::ErrorOr<std::string> P =
4240 llvm::sys::findProgramByName(TargetSpecificExecutable))
Michael J. Spencer04162ea2014-11-04 01:30:55 +00004241 return *P;
Daniel Dunbar6f668772009-03-18 21:34:08 +00004242
Daniel Dunbar1ce81532009-09-09 22:33:00 +00004243 return Name;
Daniel Dunbar5e0f6af2009-03-13 00:51:18 +00004244}
4245
Mehdi Amini12011172016-10-06 05:11:48 +00004246std::string Driver::GetTemporaryPath(StringRef Prefix, StringRef Suffix) const {
Rafael Espindola37d229d2013-06-25 04:26:55 +00004247 SmallString<128> Path;
Rafael Espindolac0809172014-06-12 14:02:15 +00004248 std::error_code EC = llvm::sys::fs::createTemporaryFile(Prefix, Suffix, Path);
Rafael Espindola37d229d2013-06-25 04:26:55 +00004249 if (EC) {
4250 Diag(clang::diag::err_unable_to_make_temp) << EC.message();
Daniel Dunbare627c1c2009-03-18 19:34:39 +00004251 return "";
4252 }
4253
Rafael Espindola37d229d2013-06-25 04:26:55 +00004254 return Path.str();
Daniel Dunbare627c1c2009-03-18 19:34:39 +00004255}
4256
Nico Weber2ca4be92016-03-01 23:16:44 +00004257std::string Driver::GetClPchPath(Compilation &C, StringRef BaseName) const {
4258 SmallString<128> Output;
4259 if (Arg *FpArg = C.getArgs().getLastArg(options::OPT__SLASH_Fp)) {
4260 // FIXME: If anybody needs it, implement this obscure rule:
4261 // "If you specify a directory without a file name, the default file name
4262 // is VCx0.pch., where x is the major version of Visual C++ in use."
4263 Output = FpArg->getValue();
4264
4265 // "If you do not specify an extension as part of the path name, an
4266 // extension of .pch is assumed. "
4267 if (!llvm::sys::path::has_extension(Output))
4268 Output += ".pch";
Erich Keane76675de2018-07-05 17:22:13 +00004269 } else if (Arg *YcArg = C.getArgs().getLastArg(options::OPT__SLASH_Yc)) {
4270 Output = YcArg->getValue();
4271 llvm::sys::path::replace_extension(Output, ".pch");
Nico Weber2ca4be92016-03-01 23:16:44 +00004272 } else {
4273 Output = BaseName;
4274 llvm::sys::path::replace_extension(Output, ".pch");
4275 }
4276 return Output.str();
4277}
4278
Chandler Carruth2ad5de12012-01-25 11:01:57 +00004279const ToolChain &Driver::getToolChain(const ArgList &Args,
Artem Belevich959e0542015-07-10 19:47:55 +00004280 const llvm::Triple &Target) const {
Chandler Carruth2ad5de12012-01-25 11:01:57 +00004281
David Blaikie6ad71012017-01-13 18:53:43 +00004282 auto &TC = ToolChains[Target.str()];
Chandler Carruth2ad5de12012-01-25 11:01:57 +00004283 if (!TC) {
4284 switch (Target.getOS()) {
Reid Kleckner330fb172016-05-11 16:19:05 +00004285 case llvm::Triple::Haiku:
David Blaikie6ad71012017-01-13 18:53:43 +00004286 TC = llvm::make_unique<toolchains::Haiku>(*this, Target, Args);
Reid Kleckner330fb172016-05-11 16:19:05 +00004287 break;
Ed Schouten4dabea22017-06-25 08:29:09 +00004288 case llvm::Triple::Ananas:
4289 TC = llvm::make_unique<toolchains::Ananas>(*this, Target, Args);
4290 break;
Ed Schouten3c3e58c2015-03-26 11:13:44 +00004291 case llvm::Triple::CloudABI:
David Blaikie6ad71012017-01-13 18:53:43 +00004292 TC = llvm::make_unique<toolchains::CloudABI>(*this, Target, Args);
Ed Schouten3c3e58c2015-03-26 11:13:44 +00004293 break;
Chandler Carruth2ad5de12012-01-25 11:01:57 +00004294 case llvm::Triple::Darwin:
4295 case llvm::Triple::MacOSX:
4296 case llvm::Triple::IOS:
Tim Northover6f3ff222015-10-30 16:30:27 +00004297 case llvm::Triple::TvOS:
4298 case llvm::Triple::WatchOS:
David Blaikie6ad71012017-01-13 18:53:43 +00004299 TC = llvm::make_unique<toolchains::DarwinClang>(*this, Target, Args);
Chandler Carruth2ad5de12012-01-25 11:01:57 +00004300 break;
4301 case llvm::Triple::DragonFly:
David Blaikie6ad71012017-01-13 18:53:43 +00004302 TC = llvm::make_unique<toolchains::DragonFly>(*this, Target, Args);
Chandler Carruth2ad5de12012-01-25 11:01:57 +00004303 break;
4304 case llvm::Triple::OpenBSD:
David Blaikie6ad71012017-01-13 18:53:43 +00004305 TC = llvm::make_unique<toolchains::OpenBSD>(*this, Target, Args);
Chandler Carruth2ad5de12012-01-25 11:01:57 +00004306 break;
4307 case llvm::Triple::NetBSD:
David Blaikie6ad71012017-01-13 18:53:43 +00004308 TC = llvm::make_unique<toolchains::NetBSD>(*this, Target, Args);
Chandler Carruth2ad5de12012-01-25 11:01:57 +00004309 break;
4310 case llvm::Triple::FreeBSD:
David Blaikie6ad71012017-01-13 18:53:43 +00004311 TC = llvm::make_unique<toolchains::FreeBSD>(*this, Target, Args);
Chandler Carruth2ad5de12012-01-25 11:01:57 +00004312 break;
4313 case llvm::Triple::Minix:
David Blaikie6ad71012017-01-13 18:53:43 +00004314 TC = llvm::make_unique<toolchains::Minix>(*this, Target, Args);
Chandler Carruth2ad5de12012-01-25 11:01:57 +00004315 break;
4316 case llvm::Triple::Linux:
Andrey Turetskiy4798eb62016-06-16 10:36:09 +00004317 case llvm::Triple::ELFIAMCU:
Chandler Carruthcf705b22012-01-25 21:03:58 +00004318 if (Target.getArch() == llvm::Triple::hexagon)
David Blaikie6ad71012017-01-13 18:53:43 +00004319 TC = llvm::make_unique<toolchains::HexagonToolChain>(*this, Target,
4320 Args);
Vasileios Kalintirisc744e122015-11-12 15:26:54 +00004321 else if ((Target.getVendor() == llvm::Triple::MipsTechnologies) &&
4322 !Target.hasEnvironment())
David Blaikie6ad71012017-01-13 18:53:43 +00004323 TC = llvm::make_unique<toolchains::MipsLLVMToolChain>(*this, Target,
4324 Args);
Chandler Carruthcf705b22012-01-25 21:03:58 +00004325 else
David Blaikie6ad71012017-01-13 18:53:43 +00004326 TC = llvm::make_unique<toolchains::Linux>(*this, Target, Args);
Chandler Carruth2ad5de12012-01-25 11:01:57 +00004327 break;
Derek Schuff6ab52fa2015-03-30 20:31:33 +00004328 case llvm::Triple::NaCl:
David Blaikie6ad71012017-01-13 18:53:43 +00004329 TC = llvm::make_unique<toolchains::NaClToolChain>(*this, Target, Args);
Derek Schuff6ab52fa2015-03-30 20:31:33 +00004330 break;
Petr Hosek62e1d232016-10-06 06:08:09 +00004331 case llvm::Triple::Fuchsia:
David Blaikie6ad71012017-01-13 18:53:43 +00004332 TC = llvm::make_unique<toolchains::Fuchsia>(*this, Target, Args);
Petr Hosek62e1d232016-10-06 06:08:09 +00004333 break;
David Chisnallf571cde2012-02-15 13:39:01 +00004334 case llvm::Triple::Solaris:
David Blaikie6ad71012017-01-13 18:53:43 +00004335 TC = llvm::make_unique<toolchains::Solaris>(*this, Target, Args);
David Chisnallf571cde2012-02-15 13:39:01 +00004336 break;
Tom Stellard8fa33092015-07-18 01:49:05 +00004337 case llvm::Triple::AMDHSA:
David Blaikie6ad71012017-01-13 18:53:43 +00004338 TC = llvm::make_unique<toolchains::AMDGPUToolChain>(*this, Target, Args);
Tom Stellard8fa33092015-07-18 01:49:05 +00004339 break;
Chandler Carruth2ad5de12012-01-25 11:01:57 +00004340 case llvm::Triple::Win32:
Saleem Abdulrasool377066a2014-03-27 22:50:18 +00004341 switch (Target.getEnvironment()) {
4342 default:
4343 if (Target.isOSBinFormatELF())
David Blaikie6ad71012017-01-13 18:53:43 +00004344 TC = llvm::make_unique<toolchains::Generic_ELF>(*this, Target, Args);
Saleem Abdulrasool377066a2014-03-27 22:50:18 +00004345 else if (Target.isOSBinFormatMachO())
David Blaikie6ad71012017-01-13 18:53:43 +00004346 TC = llvm::make_unique<toolchains::MachO>(*this, Target, Args);
Saleem Abdulrasool377066a2014-03-27 22:50:18 +00004347 else
David Blaikie6ad71012017-01-13 18:53:43 +00004348 TC = llvm::make_unique<toolchains::Generic_GCC>(*this, Target, Args);
Saleem Abdulrasool377066a2014-03-27 22:50:18 +00004349 break;
4350 case llvm::Triple::GNU:
David Blaikie6ad71012017-01-13 18:53:43 +00004351 TC = llvm::make_unique<toolchains::MinGW>(*this, Target, Args);
Saleem Abdulrasool377066a2014-03-27 22:50:18 +00004352 break;
Saleem Abdulrasool543a78b2014-10-24 03:13:37 +00004353 case llvm::Triple::Itanium:
David Blaikie6ad71012017-01-13 18:53:43 +00004354 TC = llvm::make_unique<toolchains::CrossWindowsToolChain>(*this, Target,
4355 Args);
Saleem Abdulrasool543a78b2014-10-24 03:13:37 +00004356 break;
Saleem Abdulrasool377066a2014-03-27 22:50:18 +00004357 case llvm::Triple::MSVC:
4358 case llvm::Triple::UnknownEnvironment:
Dave Leef96bedf2017-11-06 21:18:05 +00004359 if (Args.getLastArgValue(options::OPT_fuse_ld_EQ)
4360 .startswith_lower("bfd"))
4361 TC = llvm::make_unique<toolchains::CrossWindowsToolChain>(
4362 *this, Target, Args);
4363 else
4364 TC =
4365 llvm::make_unique<toolchains::MSVCToolChain>(*this, Target, Args);
Saleem Abdulrasool377066a2014-03-27 22:50:18 +00004366 break;
4367 }
Chandler Carruth2ad5de12012-01-25 11:01:57 +00004368 break;
Filipe Cabecinhasc888e192015-10-14 12:25:43 +00004369 case llvm::Triple::PS4:
David Blaikie6ad71012017-01-13 18:53:43 +00004370 TC = llvm::make_unique<toolchains::PS4CPU>(*this, Target, Args);
Filipe Cabecinhasc888e192015-10-14 12:25:43 +00004371 break;
David L Kreitzerd397ea42016-10-14 20:44:33 +00004372 case llvm::Triple::Contiki:
David Blaikie6ad71012017-01-13 18:53:43 +00004373 TC = llvm::make_unique<toolchains::Contiki>(*this, Target, Args);
David L Kreitzerd397ea42016-10-14 20:44:33 +00004374 break;
Chandler Carruth2ad5de12012-01-25 11:01:57 +00004375 default:
Douglas Katzman9f5e70e2015-05-26 18:01:33 +00004376 // Of these targets, Hexagon is the only one that might have
4377 // an OS of Linux, in which case it got handled above already.
Douglas Katzman15a63ed2015-08-12 18:36:12 +00004378 switch (Target.getArch()) {
4379 case llvm::Triple::tce:
David Blaikie6ad71012017-01-13 18:53:43 +00004380 TC = llvm::make_unique<toolchains::TCEToolChain>(*this, Target, Args);
Douglas Katzman15a63ed2015-08-12 18:36:12 +00004381 break;
Pekka Jaaskelainen67354482016-11-16 15:22:31 +00004382 case llvm::Triple::tcele:
David Blaikie6ad71012017-01-13 18:53:43 +00004383 TC = llvm::make_unique<toolchains::TCELEToolChain>(*this, Target, Args);
Pekka Jaaskelainen67354482016-11-16 15:22:31 +00004384 break;
Douglas Katzman15a63ed2015-08-12 18:36:12 +00004385 case llvm::Triple::hexagon:
David Blaikie6ad71012017-01-13 18:53:43 +00004386 TC = llvm::make_unique<toolchains::HexagonToolChain>(*this, Target,
4387 Args);
Douglas Katzman15a63ed2015-08-12 18:36:12 +00004388 break;
Jacques Pienaard964cc22016-03-28 21:02:54 +00004389 case llvm::Triple::lanai:
David Blaikie6ad71012017-01-13 18:53:43 +00004390 TC = llvm::make_unique<toolchains::LanaiToolChain>(*this, Target, Args);
Jacques Pienaard964cc22016-03-28 21:02:54 +00004391 break;
Douglas Katzman15a63ed2015-08-12 18:36:12 +00004392 case llvm::Triple::xcore:
David Blaikie6ad71012017-01-13 18:53:43 +00004393 TC = llvm::make_unique<toolchains::XCoreToolChain>(*this, Target, Args);
Douglas Katzman15a63ed2015-08-12 18:36:12 +00004394 break;
Dan Gohmanc2853072015-09-03 22:51:53 +00004395 case llvm::Triple::wasm32:
4396 case llvm::Triple::wasm64:
David Blaikie6ad71012017-01-13 18:53:43 +00004397 TC = llvm::make_unique<toolchains::WebAssembly>(*this, Target, Args);
Dan Gohmanc2853072015-09-03 22:51:53 +00004398 break;
Dylan McKay924fa3a2017-01-05 05:20:27 +00004399 case llvm::Triple::avr:
David Blaikie6ad71012017-01-13 18:53:43 +00004400 TC = llvm::make_unique<toolchains::AVRToolChain>(*this, Target, Args);
Dylan McKay924fa3a2017-01-05 05:20:27 +00004401 break;
Douglas Katzman15a63ed2015-08-12 18:36:12 +00004402 default:
Douglas Katzmand6e597c2015-09-17 19:56:40 +00004403 if (Target.getVendor() == llvm::Triple::Myriad)
David Blaikie6ad71012017-01-13 18:53:43 +00004404 TC = llvm::make_unique<toolchains::MyriadToolChain>(*this, Target,
4405 Args);
Jonathan Roelofs901c7762017-05-25 15:42:13 +00004406 else if (toolchains::BareMetal::handlesTarget(Target))
4407 TC = llvm::make_unique<toolchains::BareMetal>(*this, Target, Args);
Douglas Katzmand6e597c2015-09-17 19:56:40 +00004408 else if (Target.isOSBinFormatELF())
David Blaikie6ad71012017-01-13 18:53:43 +00004409 TC = llvm::make_unique<toolchains::Generic_ELF>(*this, Target, Args);
Douglas Katzman15a63ed2015-08-12 18:36:12 +00004410 else if (Target.isOSBinFormatMachO())
David Blaikie6ad71012017-01-13 18:53:43 +00004411 TC = llvm::make_unique<toolchains::MachO>(*this, Target, Args);
Douglas Katzman15a63ed2015-08-12 18:36:12 +00004412 else
David Blaikie6ad71012017-01-13 18:53:43 +00004413 TC = llvm::make_unique<toolchains::Generic_GCC>(*this, Target, Args);
Douglas Katzman15a63ed2015-08-12 18:36:12 +00004414 }
Chandler Carruth2ad5de12012-01-25 11:01:57 +00004415 }
4416 }
Justin Lebar66c4fd72016-11-18 00:41:22 +00004417
4418 // Intentionally omitted from the switch above: llvm::Triple::CUDA. CUDA
4419 // compiles always need two toolchains, the CUDA toolchain and the host
4420 // toolchain. So the only valid way to create a CUDA toolchain is via
4421 // CreateOffloadingDeviceToolChains.
4422
Chandler Carruth2ad5de12012-01-25 11:01:57 +00004423 return *TC;
Daniel Dunbar4dff6a42009-03-10 23:41:59 +00004424}
Daniel Dunbar8fa879d2009-03-24 18:57:02 +00004425
Rafael Espindola2f69d402013-03-18 15:33:26 +00004426bool Driver::ShouldUseClangCompiler(const JobAction &JA) const {
Douglas Katzman00249092015-06-12 15:45:21 +00004427 // Say "no" if there is not exactly one input of a type clang understands.
Nico Weber5a459f82016-02-23 19:30:43 +00004428 if (JA.size() != 1 ||
4429 !types::isAcceptedByClang((*JA.input_begin())->getType()))
Nick Lewycky5cc9ebb2012-11-15 05:36:36 +00004430 return false;
4431
Douglas Katzman00249092015-06-12 15:45:21 +00004432 // And say "no" if this is not a kind of action clang understands.
Nick Lewycky5cc9ebb2012-11-15 05:36:36 +00004433 if (!isa<PreprocessJobAction>(JA) && !isa<PrecompileJobAction>(JA) &&
Bob Wilson23a55f12014-12-21 07:00:00 +00004434 !isa<CompileJobAction>(JA) && !isa<BackendJobAction>(JA))
Nick Lewycky5cc9ebb2012-11-15 05:36:36 +00004435 return false;
4436
4437 return true;
4438}
4439
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00004440/// GetReleaseVersion - Parse (([0-9]+)(.([0-9]+)(.([0-9]+)?))?)? and return the
4441/// grouped values as integers. Numbers which are not provided are set to 0.
Daniel Dunbarc7fd57a2009-03-26 15:58:36 +00004442///
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00004443/// \return True if the entire string was parsed (9.2), or all groups were
4444/// parsed (10.3.5extrastuff).
Mehdi Amini12011172016-10-06 05:11:48 +00004445bool Driver::GetReleaseVersion(StringRef Str, unsigned &Major, unsigned &Minor,
4446 unsigned &Micro, bool &HadExtra) {
Daniel Dunbarc7fd57a2009-03-26 15:58:36 +00004447 HadExtra = false;
4448
4449 Major = Minor = Micro = 0;
Mehdi Amini12011172016-10-06 05:11:48 +00004450 if (Str.empty())
Bob Wilson433cb312015-04-07 01:03:35 +00004451 return false;
Daniel Dunbarc7fd57a2009-03-26 15:58:36 +00004452
Mehdi Amini12011172016-10-06 05:11:48 +00004453 if (Str.consumeInteger(10, Major))
4454 return false;
4455 if (Str.empty())
Daniel Dunbarc7fd57a2009-03-26 15:58:36 +00004456 return true;
Mehdi Amini12011172016-10-06 05:11:48 +00004457 if (Str[0] != '.')
Daniel Dunbarc7fd57a2009-03-26 15:58:36 +00004458 return false;
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00004459
Mehdi Amini12011172016-10-06 05:11:48 +00004460 Str = Str.drop_front(1);
Daniel Dunbarc7fd57a2009-03-26 15:58:36 +00004461
Mehdi Amini12011172016-10-06 05:11:48 +00004462 if (Str.consumeInteger(10, Minor))
Daniel Dunbarc7fd57a2009-03-26 15:58:36 +00004463 return false;
Mehdi Amini12011172016-10-06 05:11:48 +00004464 if (Str.empty())
4465 return true;
4466 if (Str[0] != '.')
4467 return false;
4468 Str = Str.drop_front(1);
4469
4470 if (Str.consumeInteger(10, Micro))
4471 return false;
4472 if (!Str.empty())
4473 HadExtra = true;
Daniel Dunbarc7fd57a2009-03-26 15:58:36 +00004474 return true;
4475}
Hans Wennborg6ddc6902013-07-27 00:23:45 +00004476
Bruno Cardoso Lopes8ed5cac2016-03-31 02:45:46 +00004477/// Parse digits from a string \p Str and fulfill \p Digits with
4478/// the parsed numbers. This method assumes that the max number of
4479/// digits to look for is equal to Digits.size().
4480///
4481/// \return True if the entire string was parsed and there are
4482/// no extra characters remaining at the end.
Mehdi Amini12011172016-10-06 05:11:48 +00004483bool Driver::GetReleaseVersion(StringRef Str,
Bruno Cardoso Lopes8ed5cac2016-03-31 02:45:46 +00004484 MutableArrayRef<unsigned> Digits) {
Mehdi Amini12011172016-10-06 05:11:48 +00004485 if (Str.empty())
Bruno Cardoso Lopes8ed5cac2016-03-31 02:45:46 +00004486 return false;
4487
Bruno Cardoso Lopes8ed5cac2016-03-31 02:45:46 +00004488 unsigned CurDigit = 0;
4489 while (CurDigit < Digits.size()) {
Mehdi Amini12011172016-10-06 05:11:48 +00004490 unsigned Digit;
4491 if (Str.consumeInteger(10, Digit))
Bruno Cardoso Lopes8ed5cac2016-03-31 02:45:46 +00004492 return false;
Mehdi Amini12011172016-10-06 05:11:48 +00004493 Digits[CurDigit] = Digit;
4494 if (Str.empty())
4495 return true;
4496 if (Str[0] != '.')
4497 return false;
4498 Str = Str.drop_front(1);
Bruno Cardoso Lopes8ed5cac2016-03-31 02:45:46 +00004499 CurDigit++;
4500 }
4501
4502 // More digits than requested, bail out...
4503 return false;
4504}
4505
Hans Wennborg6ddc6902013-07-27 00:23:45 +00004506std::pair<unsigned, unsigned> Driver::getIncludeExcludeOptionFlagMasks() const {
4507 unsigned IncludedFlagsBitmask = 0;
Rafael Espindolacc707bc2013-09-25 15:54:41 +00004508 unsigned ExcludedFlagsBitmask = options::NoDriverOption;
Hans Wennborg6ddc6902013-07-27 00:23:45 +00004509
4510 if (Mode == CLMode) {
Hans Wennborg19076102013-07-31 20:51:53 +00004511 // Include CL and Core options.
4512 IncludedFlagsBitmask |= options::CLOption;
4513 IncludedFlagsBitmask |= options::CoreOption;
Hans Wennborg6ddc6902013-07-27 00:23:45 +00004514 } else {
4515 ExcludedFlagsBitmask |= options::CLOption;
4516 }
4517
4518 return std::make_pair(IncludedFlagsBitmask, ExcludedFlagsBitmask);
4519}
Benjamin Kramerab88f622014-03-25 18:02:07 +00004520
Douglas Katzmanf08fadf2015-06-04 14:40:44 +00004521bool clang::driver::isOptimizationLevelFast(const ArgList &Args) {
Benjamin Kramerab88f622014-03-25 18:02:07 +00004522 return Args.hasFlag(options::OPT_Ofast, options::OPT_O_Group, false);
4523}