blob: 73639f378b4d3c2fdab26a0351c0210b4d8785d0 [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"
Erik Pilkington46420b62018-09-27 20:36:28 +000040#include "ToolChains/RISCVToolchain.h"
David L. Jonesf561aba2017-03-08 01:02:16 +000041#include "ToolChains/Solaris.h"
42#include "ToolChains/TCE.h"
43#include "ToolChains/WebAssembly.h"
44#include "ToolChains/XCore.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000045#include "clang/Basic/Version.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"
Fangrui Songd0028232018-10-10 00:15:33 +000070#include "llvm/Support/FormatVariadic.h"
Michael J. Spencer8aaf4992010-11-29 18:12:39 +000071#include "llvm/Support/Path.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000072#include "llvm/Support/PrettyStackTrace.h"
Hans Wennborg23d26a32014-06-18 17:21:50 +000073#include "llvm/Support/Process.h"
Michael J. Spencer8aaf4992010-11-29 18:12:39 +000074#include "llvm/Support/Program.h"
Yaxun Liuf6144222018-05-30 00:53:50 +000075#include "llvm/Support/StringSaver.h"
Dimitry Andric81c40422017-06-06 21:54:21 +000076#include "llvm/Support/TargetRegistry.h"
Jonas Devliegherefc514902018-10-10 13:27:25 +000077#include "llvm/Support/VirtualFileSystem.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000078#include "llvm/Support/raw_ostream.h"
Dylan Noblesmith4f4e7452012-02-02 00:40:14 +000079#include <map>
Ahmed Charlesdfca6f92014-03-09 11:36:40 +000080#include <memory>
Benjamin Kramercfeacf52016-05-27 14:27:13 +000081#include <utility>
Bruno Cardoso Lopes02681c42016-11-17 21:41:22 +000082#if LLVM_ON_UNIX
83#include <unistd.h> // getpid
84#endif
Dylan Noblesmith86780e92012-02-01 14:25:28 +000085
Daniel Dunbarb2cd66b2009-03-04 20:49:20 +000086using namespace clang::driver;
Chris Lattnerada1c912009-03-26 05:56:24 +000087using namespace clang;
Reid Kleckner898229a2013-06-14 17:17:23 +000088using namespace llvm::opt;
Daniel Dunbarb2cd66b2009-03-04 20:49:20 +000089
Petr Hosekdd38d932018-05-29 22:35:39 +000090Driver::Driver(StringRef ClangExecutable, StringRef TargetTriple,
Benjamin Kramerd45b2052015-10-07 15:48:01 +000091 DiagnosticsEngine &Diags,
Jonas Devliegherefc514902018-10-10 13:27:25 +000092 IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS)
Benjamin Kramercfeacf52016-05-27 14:27:13 +000093 : Opts(createDriverOptTable()), Diags(Diags), VFS(std::move(VFS)),
94 Mode(GCCMode), SaveTemps(SaveTempsNone), BitcodeEmbed(EmbedNone),
95 LTOMode(LTOK_None), ClangExecutable(ClangExecutable),
Alex Lorenz045c5142018-04-07 00:03:27 +000096 SysRoot(DEFAULT_SYSROOT), DriverTitle("clang LLVM compiler"),
97 CCPrintOptionsFilename(nullptr), CCPrintHeadersFilename(nullptr),
98 CCLogDiagnosticsFilename(nullptr), CCCPrintBindings(false),
99 CCPrintOptions(false), CCPrintHeaders(false), CCLogDiagnostics(false),
Petr Hosekdd38d932018-05-29 22:35:39 +0000100 CCGenDiagnostics(false), TargetTriple(TargetTriple),
Alex Lorenz045c5142018-04-07 00:03:27 +0000101 CCCGenericGCCName(""), Saver(Alloc), CheckInputsExist(true),
102 CCCUsePCH(true), GenReproducer(false),
103 SuppressMissingInputWarning(false) {
Daniel Dunbar3f3e2cd2010-01-20 02:35:16 +0000104
Benjamin Kramerd45b2052015-10-07 15:48:01 +0000105 // Provide a sane fallback if no VFS is specified.
106 if (!this->VFS)
Jonas Devliegherefc514902018-10-10 13:27:25 +0000107 this->VFS = llvm::vfs::getRealFileSystem();
Benjamin Kramerd45b2052015-10-07 15:48:01 +0000108
Sumanth Gundapaneni3a1592942015-03-03 20:43:12 +0000109 Name = llvm::sys::path::filename(ClangExecutable);
Douglas Katzmana67e50c2015-06-26 15:47:46 +0000110 Dir = llvm::sys::path::parent_path(ClangExecutable);
Benjamin Kramerf420dda2015-10-13 15:19:32 +0000111 InstalledDir = Dir; // Provide a sensible default installed dir.
Bob Wilsona20a1da2013-03-23 05:17:59 +0000112
Serge Pavlov208ac652018-01-01 13:27:01 +0000113#if defined(CLANG_CONFIG_FILE_SYSTEM_DIR)
114 SystemConfigDir = CLANG_CONFIG_FILE_SYSTEM_DIR;
115#endif
116#if defined(CLANG_CONFIG_FILE_USER_DIR)
117 UserConfigDir = CLANG_CONFIG_FILE_USER_DIR;
118#endif
119
Bob Wilsona20a1da2013-03-23 05:17:59 +0000120 // Compute the path to the resource directory.
121 StringRef ClangResourceDir(CLANG_RESOURCE_DIR);
122 SmallString<128> P(Dir);
Chandler Carruthfd3cc702014-12-29 12:09:08 +0000123 if (ClangResourceDir != "") {
Bob Wilsona20a1da2013-03-23 05:17:59 +0000124 llvm::sys::path::append(P, ClangResourceDir);
Chandler Carruthfd3cc702014-12-29 12:09:08 +0000125 } else {
126 StringRef ClangLibdirSuffix(CLANG_LIBDIR_SUFFIX);
Argyrios Kyrtzidisbcae0472017-02-25 18:14:35 +0000127 P = llvm::sys::path::parent_path(Dir);
128 llvm::sys::path::append(P, Twine("lib") + ClangLibdirSuffix, "clang",
Chandler Carruthfd3cc702014-12-29 12:09:08 +0000129 CLANG_VERSION_STRING);
130 }
Bob Wilsona20a1da2013-03-23 05:17:59 +0000131 ResourceDir = P.str();
Daniel Dunbar544ecd12009-03-02 19:59:07 +0000132}
133
Zachary Turneraff19c32016-08-12 17:47:52 +0000134void Driver::ParseDriverMode(StringRef ProgramName,
135 ArrayRef<const char *> Args) {
Martin Storsjo1fab23d2018-04-25 21:23:59 +0000136 if (ClangNameParts.isEmpty())
137 ClangNameParts = ToolChain::getTargetAndModeFromProgramName(ProgramName);
Serge Pavlov4e769842017-08-29 05:22:26 +0000138 setDriverModeFromOption(ClangNameParts.DriverMode);
Hans Wennborg70850d82013-07-18 20:29:38 +0000139
Douglas Katzman6bbffc42015-06-25 18:51:37 +0000140 for (const char *ArgPtr : Args) {
Erich Keane258f0592018-02-07 00:19:58 +0000141 // Ignore nullptrs, they are the response file's EOL markers.
Douglas Katzman6bbffc42015-06-25 18:51:37 +0000142 if (ArgPtr == nullptr)
Reid Kleckneraf5fd6a2014-08-22 19:29:30 +0000143 continue;
Douglas Katzman6bbffc42015-06-25 18:51:37 +0000144 const StringRef Arg = ArgPtr;
Zachary Turneraff19c32016-08-12 17:47:52 +0000145 setDriverModeFromOption(Arg);
Hans Wennborg70850d82013-07-18 20:29:38 +0000146 }
147}
148
Zachary Turneraff19c32016-08-12 17:47:52 +0000149void Driver::setDriverModeFromOption(StringRef Opt) {
150 const std::string OptName =
151 getOpts().getOption(options::OPT_driver_mode).getPrefixedName();
152 if (!Opt.startswith(OptName))
153 return;
154 StringRef Value = Opt.drop_front(OptName.size());
155
Erich Keane2908a042018-02-12 17:47:01 +0000156 if (auto M = llvm::StringSwitch<llvm::Optional<DriverMode>>(Value)
157 .Case("gcc", GCCMode)
158 .Case("g++", GXXMode)
159 .Case("cpp", CPPMode)
160 .Case("cl", CLMode)
161 .Default(None))
162 Mode = *M;
Zachary Turneraff19c32016-08-12 17:47:52 +0000163 else
164 Diag(diag::err_drv_unsupported_option_argument) << OptName << Value;
165}
166
Benjamin Kramer43c0f482017-06-30 13:21:27 +0000167InputArgList Driver::ParseArgStrings(ArrayRef<const char *> ArgStrings,
168 bool &ContainsError) {
Daniel Dunbar2608c542009-03-18 01:38:48 +0000169 llvm::PrettyStackTraceString CrashInfo("Command line argument parsing");
Benjamin Kramer43c0f482017-06-30 13:21:27 +0000170 ContainsError = false;
Hans Wennborg6ddc6902013-07-27 00:23:45 +0000171
172 unsigned IncludedFlagsBitmask;
173 unsigned ExcludedFlagsBitmask;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +0000174 std::tie(IncludedFlagsBitmask, ExcludedFlagsBitmask) =
Douglas Katzmana67e50c2015-06-26 15:47:46 +0000175 getIncludeExcludeOptionFlagMasks();
Hans Wennborg6ddc6902013-07-27 00:23:45 +0000176
Daniel Dunbar52ed5fe2009-11-19 06:35:06 +0000177 unsigned MissingArgIndex, MissingArgCount;
David Blaikie69a1d8c2015-06-22 22:07:27 +0000178 InputArgList Args =
David Blaikie6d492ad2015-06-21 06:32:36 +0000179 getOpts().ParseArgs(ArgStrings, MissingArgIndex, MissingArgCount,
180 IncludedFlagsBitmask, ExcludedFlagsBitmask);
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +0000181
Daniel Dunbar52ed5fe2009-11-19 06:35:06 +0000182 // Check for missing argument error.
Benjamin Kramer43c0f482017-06-30 13:21:27 +0000183 if (MissingArgCount) {
184 Diag(diag::err_drv_missing_argument)
David Blaikie69a1d8c2015-06-22 22:07:27 +0000185 << Args.getArgString(MissingArgIndex) << MissingArgCount;
Benjamin Kramer43c0f482017-06-30 13:21:27 +0000186 ContainsError |=
187 Diags.getDiagnosticLevel(diag::err_drv_missing_argument,
188 SourceLocation()) > DiagnosticsEngine::Warning;
189 }
Daniel Dunbar65229332009-03-13 11:38:42 +0000190
Daniel Dunbar52ed5fe2009-11-19 06:35:06 +0000191 // Check for unsupported options.
David Blaikie69a1d8c2015-06-22 22:07:27 +0000192 for (const Arg *A : Args) {
Michael J. Spencer66e2b202012-10-19 22:37:06 +0000193 if (A->getOption().hasFlag(options::Unsupported)) {
Brian Gesiak24910762018-01-06 00:25:40 +0000194 unsigned DiagID;
195 auto ArgString = A->getAsString(Args);
196 std::string Nearest;
197 if (getOpts().findNearest(
198 ArgString, Nearest, IncludedFlagsBitmask,
199 ExcludedFlagsBitmask | options::Unsupported) > 1) {
200 DiagID = diag::err_drv_unsupported_opt;
201 Diag(DiagID) << ArgString;
202 } else {
203 DiagID = diag::err_drv_unsupported_opt_with_suggestion;
204 Diag(DiagID) << ArgString << Nearest;
205 }
206 ContainsError |= Diags.getDiagnosticLevel(DiagID, SourceLocation()) >
Benjamin Kramer43c0f482017-06-30 13:21:27 +0000207 DiagnosticsEngine::Warning;
Daniel Dunbard8500f32009-03-22 23:26:43 +0000208 continue;
209 }
Chad Rosierce975d92012-02-22 17:55:22 +0000210
211 // Warn about -mcpu= without an argument.
Douglas Katzmana67e50c2015-06-26 15:47:46 +0000212 if (A->getOption().matches(options::OPT_mcpu_EQ) && A->containsValue("")) {
Benjamin Kramer43c0f482017-06-30 13:21:27 +0000213 Diag(diag::warn_drv_empty_joined_argument) << A->getAsString(Args);
214 ContainsError |= Diags.getDiagnosticLevel(
215 diag::warn_drv_empty_joined_argument,
216 SourceLocation()) > DiagnosticsEngine::Warning;
Chad Rosierce975d92012-02-22 17:55:22 +0000217 }
Daniel Dunbard02cb1d2009-03-05 06:38:47 +0000218 }
219
Benjamin Kramer43c0f482017-06-30 13:21:27 +0000220 for (const Arg *A : Args.filtered(options::OPT_UNKNOWN)) {
Brian Gesiak24910762018-01-06 00:25:40 +0000221 unsigned DiagID;
222 auto ArgString = A->getAsString(Args);
223 std::string Nearest;
224 if (getOpts().findNearest(
225 ArgString, Nearest, IncludedFlagsBitmask, ExcludedFlagsBitmask) > 1) {
226 DiagID = IsCLMode() ? diag::warn_drv_unknown_argument_clang_cl
227 : diag::err_drv_unknown_argument;
228 Diags.Report(DiagID) << ArgString;
229 } else {
230 DiagID = IsCLMode() ? diag::warn_drv_unknown_argument_clang_cl_with_suggestion
231 : diag::err_drv_unknown_argument_with_suggestion;
232 Diags.Report(DiagID) << ArgString << Nearest;
233 }
234 ContainsError |= Diags.getDiagnosticLevel(DiagID, SourceLocation()) >
Benjamin Kramer43c0f482017-06-30 13:21:27 +0000235 DiagnosticsEngine::Warning;
236 }
Rafael Espindola8a2d4962013-09-23 23:55:25 +0000237
Daniel Dunbard02cb1d2009-03-05 06:38:47 +0000238 return Args;
239}
240
Chad Rosier7742b5d2011-07-27 23:36:45 +0000241// Determine which compilation mode we are in. We look for options which
242// affect the phase, starting with the earliest phases, and record which
243// option we used to determine the final phase.
Douglas Katzmana67e50c2015-06-26 15:47:46 +0000244phases::ID Driver::getFinalPhase(const DerivedArgList &DAL,
245 Arg **FinalPhaseArg) const {
Craig Topper92fc2df2014-05-17 16:56:41 +0000246 Arg *PhaseArg = nullptr;
Chad Rosier7742b5d2011-07-27 23:36:45 +0000247 phases::ID FinalPhase;
Eric Christopherf901e852011-08-17 22:59:59 +0000248
Hans Wennborge50cec32014-06-13 20:59:54 +0000249 // -{E,EP,P,M,MM} only run the preprocessor.
Douglas Katzmana67e50c2015-06-26 15:47:46 +0000250 if (CCCIsCPP() || (PhaseArg = DAL.getLastArg(options::OPT_E)) ||
Hans Wennborge50cec32014-06-13 20:59:54 +0000251 (PhaseArg = DAL.getLastArg(options::OPT__SLASH_EP)) ||
Hans Wennborge0053472013-12-20 18:40:46 +0000252 (PhaseArg = DAL.getLastArg(options::OPT_M, options::OPT_MM)) ||
253 (PhaseArg = DAL.getLastArg(options::OPT__SLASH_P))) {
Chad Rosier7742b5d2011-07-27 23:36:45 +0000254 FinalPhase = phases::Preprocess;
Eric Christopherf901e852011-08-17 22:59:59 +0000255
Richard Smithdd4ad3d2016-08-30 19:06:26 +0000256 // --precompile only runs up to precompilation.
257 } else if ((PhaseArg = DAL.getLastArg(options::OPT__precompile))) {
258 FinalPhase = phases::Precompile;
259
Bob Wilson23a55f12014-12-21 07:00:00 +0000260 // -{fsyntax-only,-analyze,emit-ast} only run up to the compiler.
Chad Rosier7742b5d2011-07-27 23:36:45 +0000261 } else if ((PhaseArg = DAL.getLastArg(options::OPT_fsyntax_only)) ||
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +0000262 (PhaseArg = DAL.getLastArg(options::OPT_module_file_info)) ||
Ben Langmuir2cb4a782014-02-05 22:21:15 +0000263 (PhaseArg = DAL.getLastArg(options::OPT_verify_pch)) ||
Chad Rosier7742b5d2011-07-27 23:36:45 +0000264 (PhaseArg = DAL.getLastArg(options::OPT_rewrite_objc)) ||
Fariborz Jahanian73223bb2012-04-02 15:59:19 +0000265 (PhaseArg = DAL.getLastArg(options::OPT_rewrite_legacy_objc)) ||
Ted Kremenekf7639e12012-03-06 20:06:33 +0000266 (PhaseArg = DAL.getLastArg(options::OPT__migrate)) ||
Chad Rosier7742b5d2011-07-27 23:36:45 +0000267 (PhaseArg = DAL.getLastArg(options::OPT__analyze,
Chad Rosier1aeb15a2012-03-06 23:14:35 +0000268 options::OPT__analyze_auto)) ||
Bob Wilson23a55f12014-12-21 07:00:00 +0000269 (PhaseArg = DAL.getLastArg(options::OPT_emit_ast))) {
Chad Rosier7742b5d2011-07-27 23:36:45 +0000270 FinalPhase = phases::Compile;
271
Bob Wilson23a55f12014-12-21 07:00:00 +0000272 // -S only runs up to the backend.
273 } else if ((PhaseArg = DAL.getLastArg(options::OPT_S))) {
274 FinalPhase = phases::Backend;
275
Artem Belevich4242f412015-07-28 21:01:21 +0000276 // -c compilation only runs up to the assembler.
277 } else if ((PhaseArg = DAL.getLastArg(options::OPT_c))) {
Chad Rosier7742b5d2011-07-27 23:36:45 +0000278 FinalPhase = phases::Assemble;
279
280 // Otherwise do everything.
281 } else
282 FinalPhase = phases::Link;
283
284 if (FinalPhaseArg)
285 *FinalPhaseArg = PhaseArg;
286
287 return FinalPhase;
288}
289
David Blaikie0aaa7622017-01-13 17:34:15 +0000290static Arg *MakeInputArg(DerivedArgList &Args, OptTable &Opts,
Martin Storsjo665c7a42018-05-04 06:05:58 +0000291 StringRef Value, bool Claim = true) {
David Blaikie0aaa7622017-01-13 17:34:15 +0000292 Arg *A = new Arg(Opts.getOption(options::OPT_INPUT), Value,
Hans Wennborged1d0722013-08-13 21:32:29 +0000293 Args.getBaseArgs().MakeIndex(Value), Value.data());
Hans Wennborg55362852014-05-02 22:55:30 +0000294 Args.AddSynthesizedArg(A);
Martin Storsjo665c7a42018-05-04 06:05:58 +0000295 if (Claim)
296 A->claim();
Hans Wennborged1d0722013-08-13 21:32:29 +0000297 return A;
298}
299
Daniel Dunbar775d4062010-06-11 22:00:26 +0000300DerivedArgList *Driver::TranslateInputArgs(const InputArgList &Args) const {
301 DerivedArgList *DAL = new DerivedArgList(Args);
302
Daniel Dunbar2cc3f172010-09-17 00:45:02 +0000303 bool HasNostdlib = Args.hasArg(options::OPT_nostdlib);
Nirav Daveb0bb6142015-11-24 16:07:21 +0000304 bool HasNodefaultlib = Args.hasArg(options::OPT_nodefaultlibs);
Saleem Abdulrasool688b6bc2014-12-29 19:01:36 +0000305 for (Arg *A : Args) {
Daniel Dunbarfb3d7472010-06-14 21:23:12 +0000306 // Unfortunately, we have to parse some forwarding options (-Xassembler,
307 // -Xlinker, -Xpreprocessor) because we either integrate their functionality
308 // (assembler and preprocessor), or bypass a previous driver ('collect2').
Daniel Dunbar5a9d1832010-06-14 21:37:09 +0000309
310 // Rewrite linker options, to replace --no-demangle with a custom internal
311 // option.
312 if ((A->getOption().matches(options::OPT_Wl_COMMA) ||
313 A->getOption().matches(options::OPT_Xlinker)) &&
314 A->containsValue("--no-demangle")) {
Daniel Dunbarfb3d7472010-06-14 21:23:12 +0000315 // Add the rewritten no-demangle argument.
316 DAL->AddFlagArg(A, Opts->getOption(options::OPT_Z_Xlinker__no_demangle));
317
318 // Add the remaining values as Xlinker arguments.
Benjamin Kramer72e64312015-09-24 14:48:49 +0000319 for (StringRef Val : A->getValues())
Douglas Katzmana34b7bf2015-06-30 19:32:57 +0000320 if (Val != "--no-demangle")
321 DAL->AddSeparateArg(A, Opts->getOption(options::OPT_Xlinker), Val);
Daniel Dunbarfb3d7472010-06-14 21:23:12 +0000322
323 continue;
324 }
325
Daniel Dunbar5a9d1832010-06-14 21:37:09 +0000326 // Rewrite preprocessor options, to replace -Wp,-MD,FOO which is used by
327 // some build systems. We don't try to be complete here because we don't
328 // care to encourage this usage model.
329 if (A->getOption().matches(options::OPT_Wp_COMMA) &&
Richard Smithbd55daf2012-11-01 04:30:05 +0000330 (A->getValue(0) == StringRef("-MD") ||
331 A->getValue(0) == StringRef("-MMD"))) {
Daniel Dunbar3648ba72010-06-15 20:30:18 +0000332 // Rewrite to -MD/-MMD along with -MF.
Richard Smithbd55daf2012-11-01 04:30:05 +0000333 if (A->getValue(0) == StringRef("-MD"))
Daniel Dunbar3648ba72010-06-15 20:30:18 +0000334 DAL->AddFlagArg(A, Opts->getOption(options::OPT_MD));
335 else
336 DAL->AddFlagArg(A, Opts->getOption(options::OPT_MMD));
Michael J. Spencer70d85be2012-11-07 23:37:14 +0000337 if (A->getNumValues() == 2)
338 DAL->AddSeparateArg(A, Opts->getOption(options::OPT_MF),
339 A->getValue(1));
Daniel Dunbar5a9d1832010-06-14 21:37:09 +0000340 continue;
341 }
342
Shantonu Senafeb03b2010-09-17 18:39:08 +0000343 // Rewrite reserved library names.
344 if (A->getOption().matches(options::OPT_l)) {
Richard Smithbd55daf2012-11-01 04:30:05 +0000345 StringRef Value = A->getValue();
Daniel Dunbar2cc3f172010-09-17 00:45:02 +0000346
Shantonu Senafeb03b2010-09-17 18:39:08 +0000347 // Rewrite unless -nostdlib is present.
Nirav Daveb0bb6142015-11-24 16:07:21 +0000348 if (!HasNostdlib && !HasNodefaultlib && Value == "stdc++") {
Douglas Katzmana67e50c2015-06-26 15:47:46 +0000349 DAL->AddFlagArg(A, Opts->getOption(options::OPT_Z_reserved_lib_stdcxx));
Daniel Dunbar2cc3f172010-09-17 00:45:02 +0000350 continue;
351 }
Shantonu Senafeb03b2010-09-17 18:39:08 +0000352
353 // Rewrite unconditionally.
354 if (Value == "cc_kext") {
Douglas Katzmana67e50c2015-06-26 15:47:46 +0000355 DAL->AddFlagArg(A, Opts->getOption(options::OPT_Z_reserved_lib_cckext));
Shantonu Senafeb03b2010-09-17 18:39:08 +0000356 continue;
357 }
Daniel Dunbar2cc3f172010-09-17 00:45:02 +0000358 }
359
Hans Wennborged1d0722013-08-13 21:32:29 +0000360 // Pick up inputs via the -- option.
361 if (A->getOption().matches(options::OPT__DASH_DASH)) {
362 A->claim();
Benjamin Kramer72e64312015-09-24 14:48:49 +0000363 for (StringRef Val : A->getValues())
Martin Storsjo665c7a42018-05-04 06:05:58 +0000364 DAL->append(MakeInputArg(*DAL, *Opts, Val, false));
Hans Wennborged1d0722013-08-13 21:32:29 +0000365 continue;
366 }
367
Saleem Abdulrasool688b6bc2014-12-29 19:01:36 +0000368 DAL->append(A);
Daniel Dunbarfb3d7472010-06-14 21:23:12 +0000369 }
Daniel Dunbar775d4062010-06-11 22:00:26 +0000370
Andrey Turetskiy6a8b91d2016-04-21 10:16:48 +0000371 // Enforce -static if -miamcu is present.
Andrey Turetskiy5fea71c2016-06-29 10:57:17 +0000372 if (Args.hasFlag(options::OPT_miamcu, options::OPT_mno_iamcu, false))
373 DAL->AddFlagArg(0, Opts->getOption(options::OPT_static));
Andrey Turetskiy6a8b91d2016-04-21 10:16:48 +0000374
Douglas Katzmana67e50c2015-06-26 15:47:46 +0000375// Add a default value of -mlinker-version=, if one was given and the user
376// didn't specify one.
Daniel Dunbar628fcf42010-08-12 00:05:12 +0000377#if defined(HOST_LINK_VERSION)
Tim Northover018578c2015-06-12 19:21:35 +0000378 if (!Args.hasArg(options::OPT_mlinker_version_EQ) &&
379 strlen(HOST_LINK_VERSION) > 0) {
Daniel Dunbar628fcf42010-08-12 00:05:12 +0000380 DAL->AddJoinedArg(0, Opts->getOption(options::OPT_mlinker_version_EQ),
381 HOST_LINK_VERSION);
Daniel Dunbarb613ffc2010-08-17 22:32:45 +0000382 DAL->getLastArg(options::OPT_mlinker_version_EQ)->claim();
Daniel Dunbar628fcf42010-08-12 00:05:12 +0000383 }
384#endif
385
Daniel Dunbar775d4062010-06-11 22:00:26 +0000386 return DAL;
387}
388
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000389/// Compute target triple from args.
Artem Belevich959e0542015-07-10 19:47:55 +0000390///
391/// This routine provides the logic to compute a target triple from various
392/// args passed to the driver and the default triple string.
Andrey Turetskiy6a8b91d2016-04-21 10:16:48 +0000393static llvm::Triple computeTargetTriple(const Driver &D,
Petr Hosekdd38d932018-05-29 22:35:39 +0000394 StringRef TargetTriple,
Artem Belevich959e0542015-07-10 19:47:55 +0000395 const ArgList &Args,
396 StringRef DarwinArchName = "") {
397 // FIXME: Already done in Compilation *Driver::BuildCompilation
398 if (const Arg *A = Args.getLastArg(options::OPT_target))
Petr Hosekdd38d932018-05-29 22:35:39 +0000399 TargetTriple = A->getValue();
Artem Belevich959e0542015-07-10 19:47:55 +0000400
Petr Hosekdd38d932018-05-29 22:35:39 +0000401 llvm::Triple Target(llvm::Triple::normalize(TargetTriple));
Artem Belevich959e0542015-07-10 19:47:55 +0000402
403 // Handle Apple-specific options available here.
404 if (Target.isOSBinFormatMachO()) {
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +0000405 // If an explicit Darwin arch name is given, that trumps all.
Artem Belevich959e0542015-07-10 19:47:55 +0000406 if (!DarwinArchName.empty()) {
407 tools::darwin::setTripleTypeForMachOArchName(Target, DarwinArchName);
408 return Target;
409 }
410
411 // Handle the Darwin '-arch' flag.
412 if (Arg *A = Args.getLastArg(options::OPT_arch)) {
413 StringRef ArchName = A->getValue();
414 tools::darwin::setTripleTypeForMachOArchName(Target, ArchName);
415 }
416 }
417
418 // Handle pseudo-target flags '-mlittle-endian'/'-EL' and
419 // '-mbig-endian'/'-EB'.
420 if (Arg *A = Args.getLastArg(options::OPT_mlittle_endian,
421 options::OPT_mbig_endian)) {
422 if (A->getOption().matches(options::OPT_mlittle_endian)) {
423 llvm::Triple LE = Target.getLittleEndianArchVariant();
424 if (LE.getArch() != llvm::Triple::UnknownArch)
425 Target = std::move(LE);
426 } else {
427 llvm::Triple BE = Target.getBigEndianArchVariant();
428 if (BE.getArch() != llvm::Triple::UnknownArch)
429 Target = std::move(BE);
430 }
431 }
432
433 // Skip further flag support on OSes which don't support '-m32' or '-m64'.
Douglas Katzman15a63ed2015-08-12 18:36:12 +0000434 if (Target.getArch() == llvm::Triple::tce ||
435 Target.getOS() == llvm::Triple::Minix)
Artem Belevich959e0542015-07-10 19:47:55 +0000436 return Target;
437
438 // Handle pseudo-target flags '-m64', '-mx32', '-m32' and '-m16'.
Andrey Turetskiy6a8b91d2016-04-21 10:16:48 +0000439 Arg *A = Args.getLastArg(options::OPT_m64, options::OPT_mx32,
440 options::OPT_m32, options::OPT_m16);
441 if (A) {
Artem Belevich959e0542015-07-10 19:47:55 +0000442 llvm::Triple::ArchType AT = llvm::Triple::UnknownArch;
443
444 if (A->getOption().matches(options::OPT_m64)) {
445 AT = Target.get64BitArchVariant().getArch();
446 if (Target.getEnvironment() == llvm::Triple::GNUX32)
447 Target.setEnvironment(llvm::Triple::GNU);
448 } else if (A->getOption().matches(options::OPT_mx32) &&
449 Target.get64BitArchVariant().getArch() == llvm::Triple::x86_64) {
450 AT = llvm::Triple::x86_64;
451 Target.setEnvironment(llvm::Triple::GNUX32);
452 } else if (A->getOption().matches(options::OPT_m32)) {
453 AT = Target.get32BitArchVariant().getArch();
454 if (Target.getEnvironment() == llvm::Triple::GNUX32)
455 Target.setEnvironment(llvm::Triple::GNU);
456 } else if (A->getOption().matches(options::OPT_m16) &&
457 Target.get32BitArchVariant().getArch() == llvm::Triple::x86) {
458 AT = llvm::Triple::x86;
459 Target.setEnvironment(llvm::Triple::CODE16);
460 }
461
462 if (AT != llvm::Triple::UnknownArch && AT != Target.getArch())
463 Target.setArch(AT);
464 }
465
Andrey Turetskiy6a8b91d2016-04-21 10:16:48 +0000466 // Handle -miamcu flag.
Andrey Turetskiy5fea71c2016-06-29 10:57:17 +0000467 if (Args.hasFlag(options::OPT_miamcu, options::OPT_mno_iamcu, false)) {
468 if (Target.get32BitArchVariant().getArch() != llvm::Triple::x86)
469 D.Diag(diag::err_drv_unsupported_opt_for_target) << "-miamcu"
470 << Target.str();
Andrey Turetskiy6a8b91d2016-04-21 10:16:48 +0000471
Andrey Turetskiy5fea71c2016-06-29 10:57:17 +0000472 if (A && !A->getOption().matches(options::OPT_m32))
473 D.Diag(diag::err_drv_argument_not_allowed_with)
474 << "-miamcu" << A->getBaseArg().getAsString(Args);
Andrey Turetskiy6a8b91d2016-04-21 10:16:48 +0000475
Andrey Turetskiy5fea71c2016-06-29 10:57:17 +0000476 Target.setArch(llvm::Triple::x86);
477 Target.setArchName("i586");
478 Target.setEnvironment(llvm::Triple::UnknownEnvironment);
479 Target.setEnvironmentName("");
480 Target.setOS(llvm::Triple::ELFIAMCU);
481 Target.setVendor(llvm::Triple::UnknownVendor);
482 Target.setVendorName("intel");
Andrey Turetskiy6a8b91d2016-04-21 10:16:48 +0000483 }
484
Simon Atanasyan0c0fb4b2018-09-27 05:04:50 +0000485 // If target is MIPS adjust the target triple
486 // accordingly to provided ABI name.
487 A = Args.getLastArg(options::OPT_mabi_EQ);
488 if (A && Target.isMIPS())
489 Target = llvm::StringSwitch<llvm::Triple>(A->getValue())
490 .Case("32", Target.get32BitArchVariant())
491 .Case("n32", Target.get64BitArchVariant())
492 .Case("64", Target.get64BitArchVariant())
493 .Default(Target);
494
Artem Belevich959e0542015-07-10 19:47:55 +0000495 return Target;
496}
497
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000498// Parse the LTO options and record the type of LTO compilation
Teresa Johnson945bc502015-10-15 20:35:53 +0000499// based on which -f(no-)?lto(=.*)? option occurs last.
500void Driver::setLTOMode(const llvm::opt::ArgList &Args) {
501 LTOMode = LTOK_None;
502 if (!Args.hasFlag(options::OPT_flto, options::OPT_flto_EQ,
503 options::OPT_fno_lto, false))
504 return;
505
506 StringRef LTOName("full");
507
508 const Arg *A = Args.getLastArg(options::OPT_flto_EQ);
Teresa Johnson6ef80dc2015-11-02 18:03:12 +0000509 if (A)
510 LTOName = A->getValue();
Teresa Johnson945bc502015-10-15 20:35:53 +0000511
512 LTOMode = llvm::StringSwitch<LTOKind>(LTOName)
513 .Case("full", LTOK_Full)
514 .Case("thin", LTOK_Thin)
515 .Default(LTOK_Unknown);
516
517 if (LTOMode == LTOK_Unknown) {
518 assert(A);
519 Diag(diag::err_drv_unsupported_option_argument) << A->getOption().getName()
520 << A->getValue();
521 }
522}
523
Samuel Antao39f9da22016-10-27 16:38:05 +0000524/// Compute the desired OpenMP runtime from the flags provided.
525Driver::OpenMPRuntimeKind Driver::getOpenMPRuntime(const ArgList &Args) const {
526 StringRef RuntimeName(CLANG_DEFAULT_OPENMP_RUNTIME);
527
528 const Arg *A = Args.getLastArg(options::OPT_fopenmp_EQ);
529 if (A)
530 RuntimeName = A->getValue();
531
532 auto RT = llvm::StringSwitch<OpenMPRuntimeKind>(RuntimeName)
533 .Case("libomp", OMPRT_OMP)
534 .Case("libgomp", OMPRT_GOMP)
535 .Case("libiomp5", OMPRT_IOMP5)
536 .Default(OMPRT_Unknown);
537
538 if (RT == OMPRT_Unknown) {
539 if (A)
540 Diag(diag::err_drv_unsupported_option_argument)
541 << A->getOption().getName() << A->getValue();
542 else
543 // FIXME: We could use a nicer diagnostic here.
544 Diag(diag::err_drv_unsupported_opt) << "-fopenmp";
545 }
546
547 return RT;
548}
549
Samuel Antaoc1ffba52016-06-13 18:10:57 +0000550void Driver::CreateOffloadingDeviceToolChains(Compilation &C,
551 InputList &Inputs) {
552
553 //
Yaxun Liuf5a6b962018-05-11 19:21:39 +0000554 // CUDA/HIP
Samuel Antaoc1ffba52016-06-13 18:10:57 +0000555 //
Yaxun Liuf6144222018-05-30 00:53:50 +0000556 // We need to generate a CUDA/HIP toolchain if any of the inputs has a CUDA
Yaxun Liuf5a6b962018-05-11 19:21:39 +0000557 // or HIP type. However, mixed CUDA/HIP compilation is not supported.
558 bool IsCuda =
559 llvm::any_of(Inputs, [](std::pair<types::ID, const llvm::opt::Arg *> &I) {
Samuel Antaoc1ffba52016-06-13 18:10:57 +0000560 return types::isCuda(I.first);
Yaxun Liuf5a6b962018-05-11 19:21:39 +0000561 });
562 bool IsHIP =
563 llvm::any_of(Inputs,
564 [](std::pair<types::ID, const llvm::opt::Arg *> &I) {
565 return types::isHIP(I.first);
566 }) ||
567 C.getInputArgs().hasArg(options::OPT_hip_link);
568 if (IsCuda && IsHIP) {
569 Diag(clang::diag::err_drv_mix_cuda_hip);
570 return;
571 }
Yaxun Liuf6144222018-05-30 00:53:50 +0000572 if (IsCuda) {
Justin Lebar66c4fd72016-11-18 00:41:22 +0000573 const ToolChain *HostTC = C.getSingleOffloadToolChain<Action::OFK_Host>();
574 const llvm::Triple &HostTriple = HostTC->getTriple();
Yaxun Liuf5a6b962018-05-11 19:21:39 +0000575 StringRef DeviceTripleStr;
Yaxun Liuf6144222018-05-30 00:53:50 +0000576 auto OFK = Action::OFK_Cuda;
577 DeviceTripleStr =
578 HostTriple.isArch64Bit() ? "nvptx64-nvidia-cuda" : "nvptx-nvidia-cuda";
Yaxun Liuf5a6b962018-05-11 19:21:39 +0000579 llvm::Triple CudaTriple(DeviceTripleStr);
Yaxun Liuf6144222018-05-30 00:53:50 +0000580 // Use the CUDA and host triples as the key into the ToolChains map,
Yaxun Liuf5a6b962018-05-11 19:21:39 +0000581 // because the device toolchain we create depends on both.
David Blaikie6ad71012017-01-13 18:53:43 +0000582 auto &CudaTC = ToolChains[CudaTriple.str() + "/" + HostTriple.str()];
Justin Lebar66c4fd72016-11-18 00:41:22 +0000583 if (!CudaTC) {
David Blaikie6ad71012017-01-13 18:53:43 +0000584 CudaTC = llvm::make_unique<toolchains::CudaToolChain>(
Yaxun Liuf5a6b962018-05-11 19:21:39 +0000585 *this, CudaTriple, *HostTC, C.getInputArgs(), OFK);
Justin Lebar66c4fd72016-11-18 00:41:22 +0000586 }
Yaxun Liuf5a6b962018-05-11 19:21:39 +0000587 C.addOffloadDeviceToolChain(CudaTC.get(), OFK);
Yaxun Liuf6144222018-05-30 00:53:50 +0000588 } else if (IsHIP) {
589 const ToolChain *HostTC = C.getSingleOffloadToolChain<Action::OFK_Host>();
590 const llvm::Triple &HostTriple = HostTC->getTriple();
591 StringRef DeviceTripleStr;
592 auto OFK = Action::OFK_HIP;
593 DeviceTripleStr = "amdgcn-amd-amdhsa";
594 llvm::Triple HIPTriple(DeviceTripleStr);
595 // Use the HIP and host triples as the key into the ToolChains map,
596 // because the device toolchain we create depends on both.
597 auto &HIPTC = ToolChains[HIPTriple.str() + "/" + HostTriple.str()];
598 if (!HIPTC) {
599 HIPTC = llvm::make_unique<toolchains::HIPToolChain>(
600 *this, HIPTriple, *HostTC, C.getInputArgs());
601 }
602 C.addOffloadDeviceToolChain(HIPTC.get(), OFK);
Samuel Antaoc1ffba52016-06-13 18:10:57 +0000603 }
604
605 //
Samuel Antao39f9da22016-10-27 16:38:05 +0000606 // OpenMP
607 //
608 // We need to generate an OpenMP toolchain if the user specified targets with
609 // the -fopenmp-targets option.
610 if (Arg *OpenMPTargets =
611 C.getInputArgs().getLastArg(options::OPT_fopenmp_targets_EQ)) {
612 if (OpenMPTargets->getNumValues()) {
613 // We expect that -fopenmp-targets is always used in conjunction with the
614 // option -fopenmp specifying a valid runtime with offloading support,
615 // i.e. libomp or libiomp.
616 bool HasValidOpenMPRuntime = C.getInputArgs().hasFlag(
617 options::OPT_fopenmp, options::OPT_fopenmp_EQ,
618 options::OPT_fno_openmp, false);
619 if (HasValidOpenMPRuntime) {
620 OpenMPRuntimeKind OpenMPKind = getOpenMPRuntime(C.getInputArgs());
621 HasValidOpenMPRuntime =
622 OpenMPKind == OMPRT_OMP || OpenMPKind == OMPRT_IOMP5;
623 }
624
625 if (HasValidOpenMPRuntime) {
626 llvm::StringMap<const char *> FoundNormalizedTriples;
627 for (const char *Val : OpenMPTargets->getValues()) {
628 llvm::Triple TT(Val);
629 std::string NormalizedName = TT.normalize();
630
631 // Make sure we don't have a duplicate triple.
632 auto Duplicate = FoundNormalizedTriples.find(NormalizedName);
633 if (Duplicate != FoundNormalizedTriples.end()) {
634 Diag(clang::diag::warn_drv_omp_offload_target_duplicate)
635 << Val << Duplicate->second;
636 continue;
637 }
638
639 // Store the current triple so that we can check for duplicates in the
640 // following iterations.
641 FoundNormalizedTriples[NormalizedName] = Val;
642
643 // If the specified target is invalid, emit a diagnostic.
644 if (TT.getArch() == llvm::Triple::UnknownArch)
645 Diag(clang::diag::err_drv_invalid_omp_target) << Val;
646 else {
Gheorghe-Teodor Bercea6a5df722017-07-06 16:08:15 +0000647 const ToolChain *TC;
648 // CUDA toolchains have to be selected differently. They pair host
649 // and device in their implementation.
650 if (TT.isNVPTX()) {
651 const ToolChain *HostTC =
652 C.getSingleOffloadToolChain<Action::OFK_Host>();
653 assert(HostTC && "Host toolchain should be always defined.");
654 auto &CudaTC =
Gheorghe-Teodor Bercea52898432017-08-09 01:02:19 +0000655 ToolChains[TT.str() + "/" + HostTC->getTriple().normalize()];
Gheorghe-Teodor Bercea6a5df722017-07-06 16:08:15 +0000656 if (!CudaTC)
657 CudaTC = llvm::make_unique<toolchains::CudaToolChain>(
Gheorghe-Teodor Bercea2c926932017-08-08 14:33:05 +0000658 *this, TT, *HostTC, C.getInputArgs(), Action::OFK_OpenMP);
Gheorghe-Teodor Bercea6a5df722017-07-06 16:08:15 +0000659 TC = CudaTC.get();
660 } else
661 TC = &getToolChain(C.getInputArgs(), TT);
662 C.addOffloadDeviceToolChain(TC, Action::OFK_OpenMP);
Samuel Antao39f9da22016-10-27 16:38:05 +0000663 }
664 }
665 } else
666 Diag(clang::diag::err_drv_expecting_fopenmp_with_fopenmp_targets);
667 } else
668 Diag(clang::diag::warn_drv_empty_joined_argument)
669 << OpenMPTargets->getAsString(C.getInputArgs());
670 }
671
672 //
Samuel Antaoc1ffba52016-06-13 18:10:57 +0000673 // TODO: Add support for other offloading programming models here.
674 //
Samuel Antaoc1ffba52016-06-13 18:10:57 +0000675}
676
Serge Pavlov208ac652018-01-01 13:27:01 +0000677/// Looks the given directories for the specified file.
678///
679/// \param[out] FilePath File path, if the file was found.
680/// \param[in] Dirs Directories used for the search.
681/// \param[in] FileName Name of the file to search for.
682/// \return True if file was found.
683///
684/// Looks for file specified by FileName sequentially in directories specified
685/// by Dirs.
686///
687static bool searchForFile(SmallVectorImpl<char> &FilePath,
688 ArrayRef<std::string> Dirs,
689 StringRef FileName) {
690 SmallString<128> WPath;
691 for (const StringRef &Dir : Dirs) {
692 if (Dir.empty())
693 continue;
694 WPath.clear();
695 llvm::sys::path::append(WPath, Dir, FileName);
696 llvm::sys::path::native(WPath);
697 if (llvm::sys::fs::is_regular_file(WPath)) {
698 FilePath = std::move(WPath);
699 return true;
700 }
701 }
702 return false;
703}
704
705bool Driver::readConfigFile(StringRef FileName) {
706 // Try reading the given file.
707 SmallVector<const char *, 32> NewCfgArgs;
708 if (!llvm::cl::readConfigFile(FileName, Saver, NewCfgArgs)) {
709 Diag(diag::err_drv_cannot_read_config_file) << FileName;
710 return true;
711 }
712
713 // Read options from config file.
714 llvm::SmallString<128> CfgFileName(FileName);
715 llvm::sys::path::native(CfgFileName);
716 ConfigFile = CfgFileName.str();
717 bool ContainErrors;
718 CfgOptions = llvm::make_unique<InputArgList>(
719 ParseArgStrings(NewCfgArgs, ContainErrors));
720 if (ContainErrors) {
721 CfgOptions.reset();
722 return true;
723 }
724
725 if (CfgOptions->hasArg(options::OPT_config)) {
726 CfgOptions.reset();
727 Diag(diag::err_drv_nested_config_file);
728 return true;
729 }
730
731 // Claim all arguments that come from a configuration file so that the driver
732 // does not warn on any that is unused.
733 for (Arg *A : *CfgOptions)
734 A->claim();
735 return false;
736}
737
738bool Driver::loadConfigFile() {
739 std::string CfgFileName;
740 bool FileSpecifiedExplicitly = false;
741
742 // Process options that change search path for config files.
743 if (CLOptions) {
744 if (CLOptions->hasArg(options::OPT_config_system_dir_EQ)) {
745 SmallString<128> CfgDir;
746 CfgDir.append(
747 CLOptions->getLastArgValue(options::OPT_config_system_dir_EQ));
748 if (!CfgDir.empty()) {
Sam McCall296d8322018-01-02 09:35:10 +0000749 if (llvm::sys::fs::make_absolute(CfgDir).value() != 0)
Serge Pavlov208ac652018-01-01 13:27:01 +0000750 SystemConfigDir.clear();
751 else
752 SystemConfigDir = std::string(CfgDir.begin(), CfgDir.end());
753 }
754 }
755 if (CLOptions->hasArg(options::OPT_config_user_dir_EQ)) {
756 SmallString<128> CfgDir;
757 CfgDir.append(
758 CLOptions->getLastArgValue(options::OPT_config_user_dir_EQ));
759 if (!CfgDir.empty()) {
Sam McCall296d8322018-01-02 09:35:10 +0000760 if (llvm::sys::fs::make_absolute(CfgDir).value() != 0)
Serge Pavlov208ac652018-01-01 13:27:01 +0000761 UserConfigDir.clear();
762 else
763 UserConfigDir = std::string(CfgDir.begin(), CfgDir.end());
764 }
765 }
766 }
767
768 // First try to find config file specified in command line.
769 if (CLOptions) {
770 std::vector<std::string> ConfigFiles =
771 CLOptions->getAllArgValues(options::OPT_config);
772 if (ConfigFiles.size() > 1) {
773 Diag(diag::err_drv_duplicate_config);
774 return true;
775 }
776
777 if (!ConfigFiles.empty()) {
778 CfgFileName = ConfigFiles.front();
779 assert(!CfgFileName.empty());
780
781 // If argument contains directory separator, treat it as a path to
782 // configuration file.
783 if (llvm::sys::path::has_parent_path(CfgFileName)) {
784 SmallString<128> CfgFilePath;
785 if (llvm::sys::path::is_relative(CfgFileName))
786 llvm::sys::fs::current_path(CfgFilePath);
787 llvm::sys::path::append(CfgFilePath, CfgFileName);
788 if (!llvm::sys::fs::is_regular_file(CfgFilePath)) {
789 Diag(diag::err_drv_config_file_not_exist) << CfgFilePath;
790 return true;
791 }
792 return readConfigFile(CfgFilePath);
793 }
794
795 FileSpecifiedExplicitly = true;
796 }
797 }
798
799 // If config file is not specified explicitly, try to deduce configuration
800 // from executable name. For instance, an executable 'armv7l-clang' will
801 // search for config file 'armv7l-clang.cfg'.
802 if (CfgFileName.empty() && !ClangNameParts.TargetPrefix.empty())
803 CfgFileName = ClangNameParts.TargetPrefix + '-' + ClangNameParts.ModeSuffix;
804
805 if (CfgFileName.empty())
806 return false;
807
808 // Determine architecture part of the file name, if it is present.
809 StringRef CfgFileArch = CfgFileName;
810 size_t ArchPrefixLen = CfgFileArch.find('-');
811 if (ArchPrefixLen == StringRef::npos)
812 ArchPrefixLen = CfgFileArch.size();
813 llvm::Triple CfgTriple;
814 CfgFileArch = CfgFileArch.take_front(ArchPrefixLen);
815 CfgTriple = llvm::Triple(llvm::Triple::normalize(CfgFileArch));
816 if (CfgTriple.getArch() == llvm::Triple::ArchType::UnknownArch)
817 ArchPrefixLen = 0;
818
819 if (!StringRef(CfgFileName).endswith(".cfg"))
820 CfgFileName += ".cfg";
821
822 // If config file starts with architecture name and command line options
823 // redefine architecture (with options like -m32 -LE etc), try finding new
824 // config file with that architecture.
825 SmallString<128> FixedConfigFile;
826 size_t FixedArchPrefixLen = 0;
827 if (ArchPrefixLen) {
828 // Get architecture name from config file name like 'i386.cfg' or
829 // 'armv7l-clang.cfg'.
830 // Check if command line options changes effective triple.
831 llvm::Triple EffectiveTriple = computeTargetTriple(*this,
832 CfgTriple.getTriple(), *CLOptions);
833 if (CfgTriple.getArch() != EffectiveTriple.getArch()) {
834 FixedConfigFile = EffectiveTriple.getArchName();
835 FixedArchPrefixLen = FixedConfigFile.size();
836 // Append the rest of original file name so that file name transforms
837 // like: i386-clang.cfg -> x86_64-clang.cfg.
838 if (ArchPrefixLen < CfgFileName.size())
839 FixedConfigFile += CfgFileName.substr(ArchPrefixLen);
840 }
841 }
842
843 // Prepare list of directories where config file is searched for.
844 SmallVector<std::string, 3> CfgFileSearchDirs;
845 CfgFileSearchDirs.push_back(UserConfigDir);
846 CfgFileSearchDirs.push_back(SystemConfigDir);
847 CfgFileSearchDirs.push_back(Dir);
848
849 // Try to find config file. First try file with corrected architecture.
850 llvm::SmallString<128> CfgFilePath;
851 if (!FixedConfigFile.empty()) {
852 if (searchForFile(CfgFilePath, CfgFileSearchDirs, FixedConfigFile))
853 return readConfigFile(CfgFilePath);
854 // If 'x86_64-clang.cfg' was not found, try 'x86_64.cfg'.
855 FixedConfigFile.resize(FixedArchPrefixLen);
856 FixedConfigFile.append(".cfg");
857 if (searchForFile(CfgFilePath, CfgFileSearchDirs, FixedConfigFile))
858 return readConfigFile(CfgFilePath);
859 }
860
861 // Then try original file name.
862 if (searchForFile(CfgFilePath, CfgFileSearchDirs, CfgFileName))
863 return readConfigFile(CfgFilePath);
864
865 // Finally try removing driver mode part: 'x86_64-clang.cfg' -> 'x86_64.cfg'.
866 if (!ClangNameParts.ModeSuffix.empty() &&
867 !ClangNameParts.TargetPrefix.empty()) {
868 CfgFileName.assign(ClangNameParts.TargetPrefix);
869 CfgFileName.append(".cfg");
870 if (searchForFile(CfgFilePath, CfgFileSearchDirs, CfgFileName))
871 return readConfigFile(CfgFilePath);
872 }
873
874 // Report error but only if config file was specified explicitly, by option
875 // --config. If it was deduced from executable name, it is not an error.
876 if (FileSpecifiedExplicitly) {
877 Diag(diag::err_drv_config_file_not_found) << CfgFileName;
878 for (const std::string &SearchDir : CfgFileSearchDirs)
879 if (!SearchDir.empty())
880 Diag(diag::note_drv_config_file_searched_in) << SearchDir;
881 return true;
882 }
883
884 return false;
885}
886
Chris Lattner54b16772011-07-23 17:14:25 +0000887Compilation *Driver::BuildCompilation(ArrayRef<const char *> ArgList) {
Daniel Dunbar2608c542009-03-18 01:38:48 +0000888 llvm::PrettyStackTraceString CrashInfo("Compilation construction");
889
Eric Christopherf901e852011-08-17 22:59:59 +0000890 // FIXME: Handle environment options which affect driver behavior, somewhere
Bill Wendlingadbeb9f2012-03-12 21:24:57 +0000891 // (client?). GCC_EXEC_PREFIX, LPATH, CC_PRINT_OPTIONS.
Chad Rosier82301162011-09-14 00:47:55 +0000892
David Majnemer85c25b42016-07-24 17:44:03 +0000893 if (Optional<std::string> CompilerPathValue =
894 llvm::sys::Process::GetEnv("COMPILER_PATH")) {
895 StringRef CompilerPath = *CompilerPathValue;
Chad Rosier82301162011-09-14 00:47:55 +0000896 while (!CompilerPath.empty()) {
Douglas Katzmana67e50c2015-06-26 15:47:46 +0000897 std::pair<StringRef, StringRef> Split =
898 CompilerPath.split(llvm::sys::EnvPathSeparator);
Chad Rosier82301162011-09-14 00:47:55 +0000899 PrefixDirs.push_back(Split.first);
900 CompilerPath = Split.second;
901 }
902 }
Daniel Dunbar5e0f6af2009-03-13 00:51:18 +0000903
Hans Wennborg70850d82013-07-18 20:29:38 +0000904 // We look for the driver mode option early, because the mode can affect
905 // how other options are parsed.
Zachary Turneraff19c32016-08-12 17:47:52 +0000906 ParseDriverMode(ClangExecutable, ArgList.slice(1));
Hans Wennborg70850d82013-07-18 20:29:38 +0000907
Daniel Dunbar5e0f6af2009-03-13 00:51:18 +0000908 // FIXME: What are we going to do with -V and -b?
909
Serge Pavlov208ac652018-01-01 13:27:01 +0000910 // Arguments specified in command line.
911 bool ContainsError;
912 CLOptions = llvm::make_unique<InputArgList>(
913 ParseArgStrings(ArgList.slice(1), ContainsError));
914
915 // Try parsing configuration file.
916 if (!ContainsError)
917 ContainsError = loadConfigFile();
918 bool HasConfigFile = !ContainsError && (CfgOptions.get() != nullptr);
919
920 // All arguments, from both config file and command line.
921 InputArgList Args = std::move(HasConfigFile ? std::move(*CfgOptions)
922 : std::move(*CLOptions));
923 if (HasConfigFile)
924 for (auto *Opt : *CLOptions) {
Serge Pavlovf015a562018-04-26 06:28:47 +0000925 if (Opt->getOption().matches(options::OPT_config))
926 continue;
927 unsigned Index = Args.MakeIndex(Opt->getSpelling());
Serge Pavlov208ac652018-01-01 13:27:01 +0000928 const Arg *BaseArg = &Opt->getBaseArg();
929 if (BaseArg == Opt)
930 BaseArg = nullptr;
931 Arg *Copy = new llvm::opt::Arg(Opt->getOption(), Opt->getSpelling(),
Serge Pavlovf015a562018-04-26 06:28:47 +0000932 Index, BaseArg);
Serge Pavlov208ac652018-01-01 13:27:01 +0000933 Copy->getValues() = Opt->getValues();
934 if (Opt->isClaimed())
935 Copy->claim();
936 Args.append(Copy);
937 }
938
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +0000939 // FIXME: This stuff needs to go into the Compilation, not the driver.
Douglas Katzmanb7e8ef02015-06-25 19:37:41 +0000940 bool CCCPrintPhases;
Daniel Dunbard02cb1d2009-03-05 06:38:47 +0000941
Filipe Cabecinhas136f35e2015-07-18 06:35:24 +0000942 // Silence driver warnings if requested
943 Diags.setIgnoreAllWarnings(Args.hasArg(options::OPT_w));
944
Rafael Espindola59ae7992009-12-07 18:28:29 +0000945 // -no-canonical-prefixes is used very early in main.
David Blaikie69a1d8c2015-06-22 22:07:27 +0000946 Args.ClaimAllArgs(options::OPT_no_canonical_prefixes);
Rafael Espindola59ae7992009-12-07 18:28:29 +0000947
Daniel Dunbar926f81f2010-08-02 02:38:03 +0000948 // Ignore -pipe.
David Blaikie69a1d8c2015-06-22 22:07:27 +0000949 Args.ClaimAllArgs(options::OPT_pipe);
Daniel Dunbar926f81f2010-08-02 02:38:03 +0000950
Daniel Dunbaracd69572009-12-04 21:55:23 +0000951 // Extract -ccc args.
Daniel Dunbaree66cf22009-03-10 20:52:46 +0000952 //
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +0000953 // FIXME: We need to figure out where this behavior should live. Most of it
954 // should be outside in the client; the parts that aren't should have proper
955 // options, either by introducing new ones or by overloading gcc ones like -V
956 // or -b.
Douglas Katzmanb7e8ef02015-06-25 19:37:41 +0000957 CCCPrintPhases = Args.hasArg(options::OPT_ccc_print_phases);
David Blaikie69a1d8c2015-06-22 22:07:27 +0000958 CCCPrintBindings = Args.hasArg(options::OPT_ccc_print_bindings);
959 if (const Arg *A = Args.getLastArg(options::OPT_ccc_gcc_name))
Richard Smithbd55daf2012-11-01 04:30:05 +0000960 CCCGenericGCCName = A->getValue();
David Blaikie69a1d8c2015-06-22 22:07:27 +0000961 CCCUsePCH =
962 Args.hasFlag(options::OPT_ccc_pch_is_pch, options::OPT_ccc_pch_is_pth);
Bruno Cardoso Lopes52dfe712017-04-12 21:46:20 +0000963 GenReproducer = Args.hasFlag(options::OPT_gen_reproducer,
964 options::OPT_fno_crash_diagnostics,
965 !!::getenv("FORCE_CLANG_DIAGNOSTICS_CRASH"));
Petr Hosekdd38d932018-05-29 22:35:39 +0000966 // FIXME: TargetTriple is used by the target-prefixed calls to as/ld
Joerg Sonnenberger17d75512012-02-22 19:15:16 +0000967 // and getToolChain is const.
Hans Wennborg2e274592013-08-13 23:38:57 +0000968 if (IsCLMode()) {
Hans Wennborg73609a02014-03-28 01:19:04 +0000969 // clang-cl targets MSVC-style Win32.
Petr Hosekdd38d932018-05-29 22:35:39 +0000970 llvm::Triple T(TargetTriple);
Hans Wennborg9d9ce7a2014-03-28 20:49:28 +0000971 T.setOS(llvm::Triple::Win32);
Hans Wennborg0f0e8d62015-09-18 17:11:50 +0000972 T.setVendor(llvm::Triple::PC);
Hans Wennborg9d9ce7a2014-03-28 20:49:28 +0000973 T.setEnvironment(llvm::Triple::MSVC);
Oleg Ranevskyy80523182017-08-31 20:31:30 +0000974 T.setObjectFormat(llvm::Triple::COFF);
Petr Hosekdd38d932018-05-29 22:35:39 +0000975 TargetTriple = T.str();
Hans Wennborg2e274592013-08-13 23:38:57 +0000976 }
David Blaikie69a1d8c2015-06-22 22:07:27 +0000977 if (const Arg *A = Args.getLastArg(options::OPT_target))
Petr Hosekdd38d932018-05-29 22:35:39 +0000978 TargetTriple = A->getValue();
David Blaikie69a1d8c2015-06-22 22:07:27 +0000979 if (const Arg *A = Args.getLastArg(options::OPT_ccc_install_dir))
Richard Smithbd55daf2012-11-01 04:30:05 +0000980 Dir = InstalledDir = A->getValue();
David Blaikie69a1d8c2015-06-22 22:07:27 +0000981 for (const Arg *A : Args.filtered(options::OPT_B)) {
Benjamin Kramer1a648d12011-02-08 20:31:42 +0000982 A->claim();
Richard Smithbd55daf2012-11-01 04:30:05 +0000983 PrefixDirs.push_back(A->getValue(0));
Benjamin Kramer1a648d12011-02-08 20:31:42 +0000984 }
David Blaikie69a1d8c2015-06-22 22:07:27 +0000985 if (const Arg *A = Args.getLastArg(options::OPT__sysroot_EQ))
Richard Smithbd55daf2012-11-01 04:30:05 +0000986 SysRoot = A->getValue();
David Blaikie69a1d8c2015-06-22 22:07:27 +0000987 if (const Arg *A = Args.getLastArg(options::OPT__dyld_prefix_EQ))
Peter Collingbourne9d9e1fc2013-05-27 21:40:20 +0000988 DyldPrefix = A->getValue();
Daniel Dunbaree66cf22009-03-10 20:52:46 +0000989
David Blaikie69a1d8c2015-06-22 22:07:27 +0000990 if (const Arg *A = Args.getLastArg(options::OPT_resource_dir))
Bob Wilsona20a1da2013-03-23 05:17:59 +0000991 ResourceDir = A->getValue();
Jim Grosbach061dabf2013-03-12 20:17:58 +0000992
David Blaikie69a1d8c2015-06-22 22:07:27 +0000993 if (const Arg *A = Args.getLastArg(options::OPT_save_temps_EQ)) {
Reid Kleckner68eb60b2015-02-02 22:41:48 +0000994 SaveTemps = llvm::StringSwitch<SaveTempsMode>(A->getValue())
995 .Case("cwd", SaveTempsCwd)
996 .Case("obj", SaveTempsObj)
997 .Default(SaveTempsCwd);
998 }
999
Steven Wu1257cd82016-05-18 17:04:52 +00001000 setLTOMode(Args);
1001
Steven Wu844ab6a2016-11-16 06:06:44 +00001002 // Process -fembed-bitcode= flags.
1003 if (Arg *A = Args.getLastArg(options::OPT_fembed_bitcode_EQ)) {
1004 StringRef Name = A->getValue();
1005 unsigned Model = llvm::StringSwitch<unsigned>(Name)
1006 .Case("off", EmbedNone)
1007 .Case("all", EmbedBitcode)
1008 .Case("bitcode", EmbedBitcode)
1009 .Case("marker", EmbedMarker)
1010 .Default(~0U);
1011 if (Model == ~0U) {
1012 Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args)
1013 << Name;
1014 } else
1015 BitcodeEmbed = static_cast<BitcodeEmbedMode>(Model);
Steven Wu574b0f22016-03-01 01:07:58 +00001016 }
1017
David Blaikie69a1d8c2015-06-22 22:07:27 +00001018 std::unique_ptr<llvm::opt::InputArgList> UArgs =
1019 llvm::make_unique<InputArgList>(std::move(Args));
1020
Daniel Dunbar775d4062010-06-11 22:00:26 +00001021 // Perform the default argument translations.
David Blaikie69a1d8c2015-06-22 22:07:27 +00001022 DerivedArgList *TranslatedArgs = TranslateInputArgs(*UArgs);
Daniel Dunbar775d4062010-06-11 22:00:26 +00001023
Chandler Carruthcb916192012-01-25 08:49:21 +00001024 // Owned by the host.
Andrey Turetskiy6a8b91d2016-04-21 10:16:48 +00001025 const ToolChain &TC = getToolChain(
Petr Hosekdd38d932018-05-29 22:35:39 +00001026 *UArgs, computeTargetTriple(*this, TargetTriple, *UArgs));
Chandler Carruthcb916192012-01-25 08:49:21 +00001027
Daniel Dunbar3ce436d2009-03-16 06:42:30 +00001028 // The compilation takes ownership of Args.
Benjamin Kramer43c0f482017-06-30 13:21:27 +00001029 Compilation *C = new Compilation(*this, TC, UArgs.release(), TranslatedArgs,
1030 ContainsError);
Daniel Dunbarf0eddb82009-03-18 02:55:38 +00001031
Daniel Dunbarf0eddb82009-03-18 02:55:38 +00001032 if (!HandleImmediateArgs(*C))
1033 return C;
1034
Chad Rosierecdede82011-08-12 22:08:57 +00001035 // Construct the list of inputs.
1036 InputList Inputs;
Hans Wennborged1d0722013-08-13 21:32:29 +00001037 BuildInputs(C->getDefaultToolChain(), *TranslatedArgs, Inputs);
Chad Rosierecdede82011-08-12 22:08:57 +00001038
Samuel Antaoc1ffba52016-06-13 18:10:57 +00001039 // Populate the tool chains for the offloading devices, if any.
1040 CreateOffloadingDeviceToolChains(*C, Inputs);
Justin Lebar0e450a52016-03-30 23:30:25 +00001041
Chandler Carruth7f1417f2012-01-24 10:43:44 +00001042 // Construct the list of abstract actions to perform for this compilation. On
Tim Northover157d9112014-01-16 08:48:16 +00001043 // MachO targets this uses the driver-driver and universal actions.
1044 if (TC.getTriple().isOSBinFormatMachO())
Artem Belevich5e2a3ec2015-11-17 22:28:40 +00001045 BuildUniversalActions(*C, C->getDefaultToolChain(), Inputs);
Daniel Dunbarf0eddb82009-03-18 02:55:38 +00001046 else
Justin Lebar0f3474c2016-02-11 02:00:50 +00001047 BuildActions(*C, C->getArgs(), Inputs, C->getActions());
Daniel Dunbarf0eddb82009-03-18 02:55:38 +00001048
Douglas Katzmanb7e8ef02015-06-25 19:37:41 +00001049 if (CCCPrintPhases) {
Daniel Dunbareb843be2009-03-18 03:13:20 +00001050 PrintActions(*C);
Daniel Dunbarf0eddb82009-03-18 02:55:38 +00001051 return C;
1052 }
1053
1054 BuildJobs(*C);
Daniel Dunbaradc91e62009-03-15 01:38:15 +00001055
1056 return C;
Daniel Dunbaree66cf22009-03-10 20:52:46 +00001057}
1058
Justin Bognered9cbe02015-07-09 06:58:31 +00001059static void printArgList(raw_ostream &OS, const llvm::opt::ArgList &Args) {
1060 llvm::opt::ArgStringList ASL;
1061 for (const auto *A : Args)
1062 A->render(Args, ASL);
1063
1064 for (auto I = ASL.begin(), E = ASL.end(); I != E; ++I) {
1065 if (I != ASL.begin())
1066 OS << ' ';
1067 Command::printArg(OS, *I, true);
1068 }
1069 OS << '\n';
1070}
1071
Bruno Cardoso Lopes02681c42016-11-17 21:41:22 +00001072bool Driver::getCrashDiagnosticFile(StringRef ReproCrashFilename,
1073 SmallString<128> &CrashDiagDir) {
1074 using namespace llvm::sys;
1075 assert(llvm::Triple(llvm::sys::getProcessTriple()).isOSDarwin() &&
1076 "Only knows about .crash files on Darwin");
1077
1078 // The .crash file can be found on at ~/Library/Logs/DiagnosticReports/
1079 // (or /Library/Logs/DiagnosticReports for root) and has the filename pattern
1080 // clang-<VERSION>_<YYYY-MM-DD-HHMMSS>_<hostname>.crash.
1081 path::home_directory(CrashDiagDir);
1082 if (CrashDiagDir.startswith("/var/root"))
1083 CrashDiagDir = "/";
1084 path::append(CrashDiagDir, "Library/Logs/DiagnosticReports");
1085 int PID =
1086#if LLVM_ON_UNIX
1087 getpid();
1088#else
1089 0;
1090#endif
1091 std::error_code EC;
1092 fs::file_status FileStatus;
1093 TimePoint<> LastAccessTime;
1094 SmallString<128> CrashFilePath;
1095 // Lookup the .crash files and get the one generated by a subprocess spawned
1096 // by this driver invocation.
1097 for (fs::directory_iterator File(CrashDiagDir, EC), FileEnd;
1098 File != FileEnd && !EC; File.increment(EC)) {
1099 StringRef FileName = path::filename(File->path());
1100 if (!FileName.startswith(Name))
1101 continue;
1102 if (fs::status(File->path(), FileStatus))
1103 continue;
1104 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> CrashFile =
1105 llvm::MemoryBuffer::getFile(File->path());
1106 if (!CrashFile)
1107 continue;
1108 // The first line should start with "Process:", otherwise this isn't a real
1109 // .crash file.
1110 StringRef Data = CrashFile.get()->getBuffer();
1111 if (!Data.startswith("Process:"))
1112 continue;
1113 // Parse parent process pid line, e.g: "Parent Process: clang-4.0 [79141]"
1114 size_t ParentProcPos = Data.find("Parent Process:");
1115 if (ParentProcPos == StringRef::npos)
1116 continue;
1117 size_t LineEnd = Data.find_first_of("\n", ParentProcPos);
1118 if (LineEnd == StringRef::npos)
1119 continue;
1120 StringRef ParentProcess = Data.slice(ParentProcPos+15, LineEnd).trim();
1121 int OpenBracket = -1, CloseBracket = -1;
1122 for (size_t i = 0, e = ParentProcess.size(); i < e; ++i) {
1123 if (ParentProcess[i] == '[')
1124 OpenBracket = i;
1125 if (ParentProcess[i] == ']')
1126 CloseBracket = i;
1127 }
1128 // Extract the parent process PID from the .crash file and check whether
1129 // it matches this driver invocation pid.
1130 int CrashPID;
1131 if (OpenBracket < 0 || CloseBracket < 0 ||
1132 ParentProcess.slice(OpenBracket + 1, CloseBracket)
1133 .getAsInteger(10, CrashPID) || CrashPID != PID) {
1134 continue;
1135 }
1136
1137 // Found a .crash file matching the driver pid. To avoid getting an older
1138 // and misleading crash file, continue looking for the most recent.
1139 // FIXME: the driver can dispatch multiple cc1 invocations, leading to
1140 // multiple crashes poiting to the same parent process. Since the driver
1141 // does not collect pid information for the dispatched invocation there's
1142 // currently no way to distinguish among them.
1143 const auto FileAccessTime = FileStatus.getLastModificationTime();
1144 if (FileAccessTime > LastAccessTime) {
1145 CrashFilePath.assign(File->path());
1146 LastAccessTime = FileAccessTime;
1147 }
1148 }
1149
1150 // If found, copy it over to the location of other reproducer files.
1151 if (!CrashFilePath.empty()) {
1152 EC = fs::copy_file(CrashFilePath, ReproCrashFilename);
1153 if (EC)
1154 return false;
1155 return true;
1156 }
1157
1158 return false;
1159}
1160
Eric Christopherf901e852011-08-17 22:59:59 +00001161// When clang crashes, produce diagnostic information including the fully
1162// preprocessed source file(s). Request that the developer attach the
Chad Rosierbe10f982011-08-02 17:58:04 +00001163// diagnostic information to a bug report.
Alex Lorenz045c5142018-04-07 00:03:27 +00001164void Driver::generateCompilationDiagnostics(
1165 Compilation &C, const Command &FailingCommand,
1166 StringRef AdditionalInformation, CompilationDiagnosticReport *Report) {
Chad Rosier877c0a22012-02-22 00:30:39 +00001167 if (C.getArgs().hasArg(options::OPT_fno_crash_diagnostics))
Chad Rosier62135492012-07-09 17:31:28 +00001168 return;
Chad Rosierbee5a1d2012-03-07 00:30:40 +00001169
Chad Rosierdbf46a12013-02-01 18:30:26 +00001170 // Don't try to generate diagnostics for link or dsymutil jobs.
Justin Bognere1a33d12014-10-20 21:02:05 +00001171 if (FailingCommand.getCreator().isLinkJob() ||
1172 FailingCommand.getCreator().isDsymutilJob())
Chad Rosier877c0a22012-02-22 00:30:39 +00001173 return;
1174
Chad Rosier8179f112012-06-19 17:51:34 +00001175 // Print the version of the compiler.
1176 PrintVersion(C, llvm::errs());
1177
Chad Rosierbe10f982011-08-02 17:58:04 +00001178 Diag(clang::diag::note_drv_command_failed_diag_msg)
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001179 << "PLEASE submit a bug report to " BUG_REPORT_URL " and include the "
1180 "crash backtrace, preprocessed source, and associated run script.";
Chad Rosierbe10f982011-08-02 17:58:04 +00001181
1182 // Suppress driver output and emit preprocessor output to temp file.
Hans Wennborg70850d82013-07-18 20:29:38 +00001183 Mode = CPPMode;
Chad Rosierbe10f982011-08-02 17:58:04 +00001184 CCGenDiagnostics = true;
1185
Chad Rosiercdb008d2011-11-02 21:29:05 +00001186 // Save the original job command(s).
Justin Bogner25645152014-10-21 17:24:44 +00001187 Command Cmd = FailingCommand;
Chad Rosiercdb008d2011-11-02 21:29:05 +00001188
Richard Smith5bb4cdf2012-12-20 02:22:15 +00001189 // Keep track of whether we produce any errors while trying to produce
1190 // preprocessed sources.
1191 DiagnosticErrorTrap Trap(Diags);
1192
1193 // Suppress tool output.
Chad Rosierbe10f982011-08-02 17:58:04 +00001194 C.initCompilationForDiagnostics();
Chad Rosierecdede82011-08-12 22:08:57 +00001195
1196 // Construct the list of inputs.
1197 InputList Inputs;
1198 BuildInputs(C.getDefaultToolChain(), C.getArgs(), Inputs);
Chad Rosierbe10f982011-08-02 17:58:04 +00001199
Chad Rosier4f81fc22011-08-12 23:30:05 +00001200 for (InputList::iterator it = Inputs.begin(), ie = Inputs.end(); it != ie;) {
Chad Rosierd57133d2011-08-18 00:22:25 +00001201 bool IgnoreInput = false;
1202
1203 // Ignore input from stdin or any inputs that cannot be preprocessed.
Paul Robinsonf44157d2014-04-28 22:24:44 +00001204 // Check type first as not all linker inputs have a value.
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001205 if (types::getPreprocessedType(it->first) == types::TY_INVALID) {
Paul Robinsonf44157d2014-04-28 22:24:44 +00001206 IgnoreInput = true;
1207 } else if (!strcmp(it->second->getValue(), "-")) {
Chad Rosierd57133d2011-08-18 00:22:25 +00001208 Diag(clang::diag::note_drv_command_failed_diag_msg)
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001209 << "Error generating preprocessed source(s) - "
1210 "ignoring input from stdin.";
Chad Rosierd57133d2011-08-18 00:22:25 +00001211 IgnoreInput = true;
Chad Rosierd57133d2011-08-18 00:22:25 +00001212 }
1213
1214 if (IgnoreInput) {
Chad Rosier4f81fc22011-08-12 23:30:05 +00001215 it = Inputs.erase(it);
1216 ie = Inputs.end();
Chad Rosier6fdf38b2011-08-17 23:08:45 +00001217 } else {
Chad Rosier4f81fc22011-08-12 23:30:05 +00001218 ++it;
Chad Rosier6fdf38b2011-08-17 23:08:45 +00001219 }
Chad Rosier4f81fc22011-08-12 23:30:05 +00001220 }
Chad Rosierd57133d2011-08-18 00:22:25 +00001221
Chad Rosierc5103c32013-01-29 23:57:10 +00001222 if (Inputs.empty()) {
1223 Diag(clang::diag::note_drv_command_failed_diag_msg)
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001224 << "Error generating preprocessed source(s) - "
1225 "no preprocessable inputs.";
Chad Rosierc5103c32013-01-29 23:57:10 +00001226 return;
1227 }
1228
Chad Rosiere75ef402011-09-06 23:52:36 +00001229 // Don't attempt to generate preprocessed files if multiple -arch options are
Chad Rosier636d2832012-02-13 18:16:28 +00001230 // used, unless they're all duplicates.
1231 llvm::StringSet<> ArchNames;
Saleem Abdulrasool688b6bc2014-12-29 19:01:36 +00001232 for (const Arg *A : C.getArgs()) {
Chad Rosiere75ef402011-09-06 23:52:36 +00001233 if (A->getOption().matches(options::OPT_arch)) {
Richard Smithbd55daf2012-11-01 04:30:05 +00001234 StringRef ArchName = A->getValue();
Chad Rosier636d2832012-02-13 18:16:28 +00001235 ArchNames.insert(ArchName);
Chad Rosiere75ef402011-09-06 23:52:36 +00001236 }
1237 }
Chad Rosier636d2832012-02-13 18:16:28 +00001238 if (ArchNames.size() > 1) {
1239 Diag(clang::diag::note_drv_command_failed_diag_msg)
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001240 << "Error generating preprocessed source(s) - cannot generate "
1241 "preprocessed source with multiple -arch options.";
Chad Rosier636d2832012-02-13 18:16:28 +00001242 return;
1243 }
Chad Rosiere75ef402011-09-06 23:52:36 +00001244
Chandler Carruth7f1417f2012-01-24 10:43:44 +00001245 // Construct the list of abstract actions to perform for this compilation. On
1246 // Darwin OSes this uses the driver-driver and builds universal actions.
Chandler Carruthcb916192012-01-25 08:49:21 +00001247 const ToolChain &TC = C.getDefaultToolChain();
Tim Northover157d9112014-01-16 08:48:16 +00001248 if (TC.getTriple().isOSBinFormatMachO())
Artem Belevich5e2a3ec2015-11-17 22:28:40 +00001249 BuildUniversalActions(C, TC, Inputs);
Chad Rosierbe10f982011-08-02 17:58:04 +00001250 else
Justin Lebar0f3474c2016-02-11 02:00:50 +00001251 BuildActions(C, C.getArgs(), Inputs, C.getActions());
Chad Rosierbe10f982011-08-02 17:58:04 +00001252
1253 BuildJobs(C);
1254
1255 // If there were errors building the compilation, quit now.
Richard Smith5bb4cdf2012-12-20 02:22:15 +00001256 if (Trap.hasErrorOccurred()) {
Chad Rosierbe10f982011-08-02 17:58:04 +00001257 Diag(clang::diag::note_drv_command_failed_diag_msg)
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001258 << "Error generating preprocessed source(s).";
Chad Rosierbe10f982011-08-02 17:58:04 +00001259 return;
1260 }
1261
1262 // Generate preprocessed output.
Chad Rosierdd60e092013-01-29 20:15:05 +00001263 SmallVector<std::pair<int, const Command *>, 4> FailingCommands;
Justin Bogner0cd92482015-07-02 22:52:08 +00001264 C.ExecuteJobs(C.getJobs(), FailingCommands);
Chad Rosierbe10f982011-08-02 17:58:04 +00001265
Justin Bognerbc89b182014-10-20 21:20:27 +00001266 // If any of the preprocessing commands failed, clean up and exit.
1267 if (!FailingCommands.empty()) {
Chad Rosierbe10f982011-08-02 17:58:04 +00001268 Diag(clang::diag::note_drv_command_failed_diag_msg)
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001269 << "Error generating preprocessed source(s).";
Justin Bognerbc89b182014-10-20 21:20:27 +00001270 return;
Chad Rosierbe10f982011-08-02 17:58:04 +00001271 }
Justin Bognerbc89b182014-10-20 21:20:27 +00001272
Justin Bognerc1fdf7f2014-10-20 21:47:56 +00001273 const ArgStringList &TempFiles = C.getTempFiles();
1274 if (TempFiles.empty()) {
1275 Diag(clang::diag::note_drv_command_failed_diag_msg)
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001276 << "Error generating preprocessed source(s).";
Justin Bognerc1fdf7f2014-10-20 21:47:56 +00001277 return;
1278 }
1279
Justin Bognerbc89b182014-10-20 21:20:27 +00001280 Diag(clang::diag::note_drv_command_failed_diag_msg)
1281 << "\n********************\n\n"
1282 "PLEASE ATTACH THE FOLLOWING FILES TO THE BUG REPORT:\n"
1283 "Preprocessed source(s) and associated run script(s) are located at:";
Justin Bognerbc89b182014-10-20 21:20:27 +00001284
Justin Bogner659ecc32014-10-20 22:47:23 +00001285 SmallString<128> VFS;
Bruno Cardoso Lopes02681c42016-11-17 21:41:22 +00001286 SmallString<128> ReproCrashFilename;
Justin Bogner659ecc32014-10-20 22:47:23 +00001287 for (const char *TempFile : TempFiles) {
Justin Bognerc1fdf7f2014-10-20 21:47:56 +00001288 Diag(clang::diag::note_drv_command_failed_diag_msg) << TempFile;
Alex Lorenz045c5142018-04-07 00:03:27 +00001289 if (Report)
1290 Report->TemporaryFiles.push_back(TempFile);
Bruno Cardoso Lopes02681c42016-11-17 21:41:22 +00001291 if (ReproCrashFilename.empty()) {
1292 ReproCrashFilename = TempFile;
1293 llvm::sys::path::replace_extension(ReproCrashFilename, ".crash");
1294 }
Justin Bogner659ecc32014-10-20 22:47:23 +00001295 if (StringRef(TempFile).endswith(".cache")) {
1296 // In some cases (modules) we'll dump extra data to help with reproducing
1297 // the crash into a directory next to the output.
1298 VFS = llvm::sys::path::filename(TempFile);
1299 llvm::sys::path::append(VFS, "vfs", "vfs.yaml");
1300 }
1301 }
Justin Bognerc1fdf7f2014-10-20 21:47:56 +00001302
1303 // Assume associated files are based off of the first temporary file.
Justin Bogner25645152014-10-21 17:24:44 +00001304 CrashReportInfo CrashInfo(TempFiles[0], VFS);
Justin Bognerc1fdf7f2014-10-20 21:47:56 +00001305
Bob Haarman7e4d3ff2018-07-09 21:07:20 +00001306 llvm::SmallString<128> Script(CrashInfo.Filename);
1307 llvm::sys::path::replace_extension(Script, "sh");
Justin Bognerc1fdf7f2014-10-20 21:47:56 +00001308 std::error_code EC;
Zachary Turner1f67a3c2018-06-07 19:58:58 +00001309 llvm::raw_fd_ostream ScriptOS(Script, EC, llvm::sys::fs::CD_CreateNew);
Justin Bognerc1fdf7f2014-10-20 21:47:56 +00001310 if (EC) {
1311 Diag(clang::diag::note_drv_command_failed_diag_msg)
Bob Haarman7e4d3ff2018-07-09 21:07:20 +00001312 << "Error generating run script: " << Script << " " << EC.message();
Justin Bognerc1fdf7f2014-10-20 21:47:56 +00001313 } else {
Justin Bogner42220ed2015-03-12 00:14:35 +00001314 ScriptOS << "# Crash reproducer for " << getClangFullVersion() << "\n"
Justin Bognered9cbe02015-07-09 06:58:31 +00001315 << "# Driver args: ";
1316 printArgList(ScriptOS, C.getInputArgs());
1317 ScriptOS << "# Original command: ";
Justin Bogner42220ed2015-03-12 00:14:35 +00001318 Cmd.Print(ScriptOS, "\n", /*Quote=*/true);
Justin Bogner33bdbc62014-10-21 18:03:08 +00001319 Cmd.Print(ScriptOS, "\n", /*Quote=*/true, &CrashInfo);
Alex Lorenz045c5142018-04-07 00:03:27 +00001320 if (!AdditionalInformation.empty())
1321 ScriptOS << "\n# Additional information: " << AdditionalInformation
1322 << "\n";
1323 if (Report)
Bob Haarman7e4d3ff2018-07-09 21:07:20 +00001324 Report->TemporaryFiles.push_back(Script.str());
Justin Bognerc1fdf7f2014-10-20 21:47:56 +00001325 Diag(clang::diag::note_drv_command_failed_diag_msg) << Script;
Justin Bognerbc89b182014-10-20 21:20:27 +00001326 }
Saleem Abdulrasool3661a822015-01-12 02:33:09 +00001327
Bruno Cardoso Lopes02681c42016-11-17 21:41:22 +00001328 // On darwin, provide information about the .crash diagnostic report.
1329 if (llvm::Triple(llvm::sys::getProcessTriple()).isOSDarwin()) {
1330 SmallString<128> CrashDiagDir;
1331 if (getCrashDiagnosticFile(ReproCrashFilename, CrashDiagDir)) {
1332 Diag(clang::diag::note_drv_command_failed_diag_msg)
1333 << ReproCrashFilename.str();
1334 } else { // Suggest a directory for the user to look for .crash files.
1335 llvm::sys::path::append(CrashDiagDir, Name);
1336 CrashDiagDir += "_<YYYY-MM-DD-HHMMSS>_<hostname>.crash";
1337 Diag(clang::diag::note_drv_command_failed_diag_msg)
1338 << "Crash backtrace is located in";
1339 Diag(clang::diag::note_drv_command_failed_diag_msg)
1340 << CrashDiagDir.str();
1341 Diag(clang::diag::note_drv_command_failed_diag_msg)
1342 << "(choose the .crash file that corresponds to your crash)";
1343 }
1344 }
1345
Saleem Abdulrasool3661a822015-01-12 02:33:09 +00001346 for (const auto &A : C.getArgs().filtered(options::OPT_frewrite_map_file,
1347 options::OPT_frewrite_map_file_EQ))
1348 Diag(clang::diag::note_drv_command_failed_diag_msg) << A->getValue();
1349
Justin Bognerbc89b182014-10-20 21:20:27 +00001350 Diag(clang::diag::note_drv_command_failed_diag_msg)
1351 << "\n\n********************";
Chad Rosierbe10f982011-08-02 17:58:04 +00001352}
1353
Justin Bogner0cd92482015-07-02 22:52:08 +00001354void Driver::setUpResponseFiles(Compilation &C, Command &Cmd) {
Oleg Ranevskyycd516372016-01-05 19:54:39 +00001355 // Since commandLineFitsWithinSystemLimits() may underestimate system's capacity
Reid Kleckner0290c9c2014-09-15 17:45:39 +00001356 // if the tool does not support response files, there is a chance/ that things
1357 // will just work without a response file, so we silently just skip it.
Justin Bogner0cd92482015-07-02 22:52:08 +00001358 if (Cmd.getCreator().getResponseFilesSupport() == Tool::RF_None ||
Oleg Ranevskyycd516372016-01-05 19:54:39 +00001359 llvm::sys::commandLineFitsWithinSystemLimits(Cmd.getExecutable(), Cmd.getArguments()))
Reid Kleckner0290c9c2014-09-15 17:45:39 +00001360 return;
1361
1362 std::string TmpName = GetTemporaryPath("response", "txt");
Malcolm Parsonsf76f6502016-11-02 10:39:27 +00001363 Cmd.setResponseFile(C.addTempFile(C.getArgs().MakeArgString(TmpName)));
Reid Kleckner0290c9c2014-09-15 17:45:39 +00001364}
1365
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001366int Driver::ExecuteCompilation(
1367 Compilation &C,
1368 SmallVectorImpl<std::pair<int, const Command *>> &FailingCommands) {
Daniel Dunbar38bfda62009-07-01 20:03:04 +00001369 // Just print if -### was present.
1370 if (C.getArgs().hasArg(options::OPT__HASH_HASH_HASH)) {
Hans Wennborgb212b342013-09-12 18:23:34 +00001371 C.getJobs().Print(llvm::errs(), "\n", true);
Daniel Dunbar38bfda62009-07-01 20:03:04 +00001372 return 0;
1373 }
1374
1375 // If there were errors building the compilation, quit now.
Chad Rosierbe10f982011-08-02 17:58:04 +00001376 if (Diags.hasErrorOccurred())
Daniel Dunbar38bfda62009-07-01 20:03:04 +00001377 return 1;
1378
Reid Kleckner0290c9c2014-09-15 17:45:39 +00001379 // Set up response file names for each command, if necessary
Justin Bogner0cd92482015-07-02 22:52:08 +00001380 for (auto &Job : C.getJobs())
1381 setUpResponseFiles(C, Job);
Reid Kleckner0290c9c2014-09-15 17:45:39 +00001382
Justin Bogner0cd92482015-07-02 22:52:08 +00001383 C.ExecuteJobs(C.getJobs(), FailingCommands);
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001384
Daniel Dunbar07494792010-05-22 00:37:20 +00001385 // If the command succeeded, we are done.
Chad Rosierdd60e092013-01-29 20:15:05 +00001386 if (FailingCommands.empty())
1387 return 0;
Daniel Dunbar07494792010-05-22 00:37:20 +00001388
Chad Rosierdd60e092013-01-29 20:15:05 +00001389 // Otherwise, remove result files and print extra information about abnormal
1390 // failures.
Douglas Katzman6bbffc42015-06-25 18:51:37 +00001391 for (const auto &CmdPair : FailingCommands) {
1392 int Res = CmdPair.first;
1393 const Command *FailingCommand = CmdPair.second;
Daniel Dunbar38bfda62009-07-01 20:03:04 +00001394
Chad Rosierdd60e092013-01-29 20:15:05 +00001395 // Remove result files if we're not saving temps.
Reid Kleckner68eb60b2015-02-02 22:41:48 +00001396 if (!isSaveTempsEnabled()) {
Chad Rosierdd60e092013-01-29 20:15:05 +00001397 const JobAction *JA = cast<JobAction>(&FailingCommand->getSource());
1398 C.CleanupFileMap(C.getResultFiles(), JA, true);
1399
1400 // Failure result files are valid unless we crashed.
1401 if (Res < 0)
1402 C.CleanupFileMap(C.getFailureResultFiles(), JA, true);
1403 }
1404
1405 // Print extra information about abnormal failures, if possible.
1406 //
1407 // This is ad-hoc, but we don't want to be excessively noisy. If the result
Justin Bogner5aaf2e72014-06-26 20:59:36 +00001408 // status was 1, assume the command failed normally. In particular, if it
Chad Rosierdd60e092013-01-29 20:15:05 +00001409 // was the compiler then assume it gave a reasonable error code. Failures
1410 // in other tools are less common, and they generally have worse
1411 // diagnostics, so always print the diagnostic there.
1412 const Tool &FailingTool = FailingCommand->getCreator();
1413
1414 if (!FailingCommand->getCreator().hasGoodDiagnostics() || Res != 1) {
1415 // FIXME: See FIXME above regarding result code interpretation.
1416 if (Res < 0)
1417 Diag(clang::diag::err_drv_command_signalled)
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001418 << FailingTool.getShortName();
Chad Rosierdd60e092013-01-29 20:15:05 +00001419 else
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001420 Diag(clang::diag::err_drv_command_failed) << FailingTool.getShortName()
1421 << Res;
Chad Rosierdd60e092013-01-29 20:15:05 +00001422 }
Peter Collingbourne119cfaa2011-11-21 00:01:05 +00001423 }
Chad Rosierdd60e092013-01-29 20:15:05 +00001424 return 0;
Daniel Dunbar38bfda62009-07-01 20:03:04 +00001425}
1426
Daniel Dunbara7b5e212009-04-15 16:34:29 +00001427void Driver::PrintHelp(bool ShowHidden) const {
Hans Wennborg6ddc6902013-07-27 00:23:45 +00001428 unsigned IncludedFlagsBitmask;
1429 unsigned ExcludedFlagsBitmask;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00001430 std::tie(IncludedFlagsBitmask, ExcludedFlagsBitmask) =
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001431 getIncludeExcludeOptionFlagMasks();
Hans Wennborg6ddc6902013-07-27 00:23:45 +00001432
1433 ExcludedFlagsBitmask |= options::NoDriverOption;
1434 if (!ShowHidden)
1435 ExcludedFlagsBitmask |= HelpHidden;
1436
Fangrui Songd0028232018-10-10 00:15:33 +00001437 std::string Usage = llvm::formatv("{0} [options] file...", Name).str();
1438 getOpts().PrintHelp(llvm::outs(), Usage.c_str(), DriverTitle.c_str(),
George Rimar5dbfa4e2017-07-26 09:10:17 +00001439 IncludedFlagsBitmask, ExcludedFlagsBitmask,
1440 /*ShowAllAliases=*/false);
Daniel Dunbar7c925282009-03-31 21:38:17 +00001441}
1442
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001443void Driver::PrintVersion(const Compilation &C, raw_ostream &OS) const {
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001444 // FIXME: The following handlers should use a callback mechanism, we don't
1445 // know what the client would like to do.
Ted Kremenek4c0df3d2010-01-23 02:11:34 +00001446 OS << getClangFullVersion() << '\n';
Daniel Dunbarb10248802009-03-26 16:09:13 +00001447 const ToolChain &TC = C.getDefaultToolChain();
Daniel Dunbar08e41d62009-07-21 20:06:58 +00001448 OS << "Target: " << TC.getTripleString() << '\n';
Daniel Dunbar10978e42009-06-16 23:32:58 +00001449
1450 // Print the threading model.
Jonathan Roelofsb140a102014-10-03 21:57:44 +00001451 if (Arg *A = C.getArgs().getLastArg(options::OPT_mthread_model)) {
1452 // Don't print if the ToolChain would have barfed on it already
1453 if (TC.isThreadModelSupported(A->getValue()))
1454 OS << "Thread model: " << A->getValue();
1455 } else
1456 OS << "Thread model: " << TC.getThreadModel();
1457 OS << '\n';
Chandler Carruth9ade6a92015-08-05 17:07:33 +00001458
1459 // Print out the install directory.
1460 OS << "InstalledDir: " << InstalledDir << '\n';
Serge Pavlov208ac652018-01-01 13:27:01 +00001461
1462 // If configuration file was used, print its path.
1463 if (!ConfigFile.empty())
1464 OS << "Configuration file: " << ConfigFile << '\n';
Daniel Dunbar5e0f6af2009-03-13 00:51:18 +00001465}
1466
Chris Lattner86ed5b02010-05-05 05:53:24 +00001467/// PrintDiagnosticCategories - Implement the --print-diagnostic-categories
1468/// option.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001469static void PrintDiagnosticCategories(raw_ostream &OS) {
Argyrios Kyrtzidis0e37afa2011-05-25 05:05:01 +00001470 // Skip the empty category.
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001471 for (unsigned i = 1, max = DiagnosticIDs::getNumberOfCategories(); i != max;
1472 ++i)
Argyrios Kyrtzidis0e37afa2011-05-25 05:05:01 +00001473 OS << i << ',' << DiagnosticIDs::getCategoryNameFromID(i) << '\n';
Chris Lattner86ed5b02010-05-05 05:53:24 +00001474}
1475
Yuka Takahashi41789e42018-03-05 08:54:20 +00001476void Driver::HandleAutocompletions(StringRef PassedFlags) const {
Yuka Takahashi503da8f2018-03-05 09:01:31 +00001477 if (PassedFlags == "")
1478 return;
Yuka Takahashi1a895202017-08-29 17:46:46 +00001479 // Print out all options that start with a given argument. This is used for
1480 // shell autocompletion.
1481 std::vector<std::string> SuggestedCompletions;
Yuka Takahashi41789e42018-03-05 08:54:20 +00001482 std::vector<std::string> Flags;
Yuka Takahashi1a895202017-08-29 17:46:46 +00001483
1484 unsigned short DisableFlags =
1485 options::NoDriverOption | options::Unsupported | options::Ignored;
Yuka Takahashi41789e42018-03-05 08:54:20 +00001486
1487 // Parse PassedFlags by "," as all the command-line flags are passed to this
1488 // function separated by ","
1489 StringRef TargetFlags = PassedFlags;
1490 while (TargetFlags != "") {
1491 StringRef CurFlag;
1492 std::tie(CurFlag, TargetFlags) = TargetFlags.split(",");
1493 Flags.push_back(std::string(CurFlag));
Yuka Takahashi1a895202017-08-29 17:46:46 +00001494 }
1495
Yuka Takahashi41789e42018-03-05 08:54:20 +00001496 // We want to show cc1-only options only when clang is invoked with -cc1 or
1497 // -Xclang.
Yuka Takahashi503da8f2018-03-05 09:01:31 +00001498 if (std::find(Flags.begin(), Flags.end(), "-Xclang") != Flags.end() ||
1499 std::find(Flags.begin(), Flags.end(), "-cc1") != Flags.end())
Yuka Takahashi41789e42018-03-05 08:54:20 +00001500 DisableFlags &= ~options::NoDriverOption;
1501
1502 StringRef Cur;
1503 Cur = Flags.at(Flags.size() - 1);
1504 StringRef Prev;
1505 if (Flags.size() >= 2) {
1506 Prev = Flags.at(Flags.size() - 2);
1507 SuggestedCompletions = Opts->suggestValueCompletions(Prev, Cur);
1508 }
1509
1510 if (SuggestedCompletions.empty())
1511 SuggestedCompletions = Opts->suggestValueCompletions(Cur, "");
1512
1513 if (SuggestedCompletions.empty()) {
Yuka Takahashi1a895202017-08-29 17:46:46 +00001514 // If the flag is in the form of "--autocomplete=-foo",
1515 // we were requested to print out all option names that start with "-foo".
1516 // For example, "--autocomplete=-fsyn" is expanded to "-fsyntax-only".
Yuka Takahashi41789e42018-03-05 08:54:20 +00001517 SuggestedCompletions = Opts->findByPrefix(Cur, DisableFlags);
Yuka Takahashi1a895202017-08-29 17:46:46 +00001518
1519 // We have to query the -W flags manually as they're not in the OptTable.
1520 // TODO: Find a good way to add them to OptTable instead and them remove
1521 // this code.
1522 for (StringRef S : DiagnosticIDs::getDiagnosticFlags())
Yuka Takahashi41789e42018-03-05 08:54:20 +00001523 if (S.startswith(Cur))
Yuka Takahashi1a895202017-08-29 17:46:46 +00001524 SuggestedCompletions.push_back(S);
Yuka Takahashi1a895202017-08-29 17:46:46 +00001525 }
1526
1527 // Sort the autocomplete candidates so that shells print them out in a
1528 // deterministic order. We could sort in any way, but we chose
1529 // case-insensitive sorting for consistency with the -help option
1530 // which prints out options in the case-insensitive alphabetical order.
Fangrui Song55fab262018-09-26 22:16:28 +00001531 llvm::sort(SuggestedCompletions, [](StringRef A, StringRef B) {
1532 if (int X = A.compare_lower(B))
1533 return X < 0;
1534 return A.compare(B) > 0;
1535 });
Yuka Takahashi1a895202017-08-29 17:46:46 +00001536
1537 llvm::outs() << llvm::join(SuggestedCompletions, "\n") << '\n';
1538}
1539
Daniel Dunbarf0eddb82009-03-18 02:55:38 +00001540bool Driver::HandleImmediateArgs(const Compilation &C) {
Daniel Dunbar18974bd2010-06-11 22:00:19 +00001541 // The order these options are handled in gcc is all over the place, but we
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001542 // don't expect inconsistencies w.r.t. that to matter in practice.
Daniel Dunbar7c925282009-03-31 21:38:17 +00001543
Daniel Dunbar1b09e042010-09-17 02:47:28 +00001544 if (C.getArgs().hasArg(options::OPT_dumpmachine)) {
1545 llvm::outs() << C.getDefaultToolChain().getTripleString() << '\n';
1546 return false;
1547 }
1548
Daniel Dunbara9bbcfa2009-04-04 05:17:38 +00001549 if (C.getArgs().hasArg(options::OPT_dumpversion)) {
Daniel Dunbare26e5002011-01-12 00:43:47 +00001550 // Since -dumpversion is only implemented for pedantic GCC compatibility, we
1551 // return an answer which matches our definition of __VERSION__.
1552 //
1553 // If we want to return a more correct answer some day, then we should
1554 // introduce a non-pedantically GCC compatible mode to Clang in which we
1555 // provide sensible definitions for -dumpversion, __VERSION__, etc.
1556 llvm::outs() << "4.2.1\n";
Daniel Dunbara9bbcfa2009-04-04 05:17:38 +00001557 return false;
1558 }
Daniel Dunbarfb3d7472010-06-14 21:23:12 +00001559
Chris Lattner86ed5b02010-05-05 05:53:24 +00001560 if (C.getArgs().hasArg(options::OPT__print_diagnostic_categories)) {
1561 PrintDiagnosticCategories(llvm::outs());
1562 return false;
1563 }
Daniel Dunbara9bbcfa2009-04-04 05:17:38 +00001564
James Molloya3c85b82012-05-01 14:57:16 +00001565 if (C.getArgs().hasArg(options::OPT_help) ||
Daniel Dunbara7b5e212009-04-15 16:34:29 +00001566 C.getArgs().hasArg(options::OPT__help_hidden)) {
1567 PrintHelp(C.getArgs().hasArg(options::OPT__help_hidden));
Daniel Dunbar7c925282009-03-31 21:38:17 +00001568 return false;
1569 }
1570
Daniel Dunbarb0006ae2009-04-02 15:05:41 +00001571 if (C.getArgs().hasArg(options::OPT__version)) {
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001572 // Follow gcc behavior and use stdout for --version and stderr for -v.
Daniel Dunbar08e41d62009-07-21 20:06:58 +00001573 PrintVersion(C, llvm::outs());
Daniel Dunbarb0006ae2009-04-02 15:05:41 +00001574 return false;
1575 }
1576
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001577 if (C.getArgs().hasArg(options::OPT_v) ||
Daniel Dunbarf0eddb82009-03-18 02:55:38 +00001578 C.getArgs().hasArg(options::OPT__HASH_HASH_HASH)) {
Daniel Dunbar08e41d62009-07-21 20:06:58 +00001579 PrintVersion(C, llvm::errs());
Daniel Dunbar5e0f6af2009-03-13 00:51:18 +00001580 SuppressMissingInputWarning = true;
1581 }
1582
Serge Pavlov208ac652018-01-01 13:27:01 +00001583 if (C.getArgs().hasArg(options::OPT_v)) {
1584 if (!SystemConfigDir.empty())
1585 llvm::errs() << "System configuration file directory: "
1586 << SystemConfigDir << "\n";
1587 if (!UserConfigDir.empty())
1588 llvm::errs() << "User configuration file directory: "
1589 << UserConfigDir << "\n";
1590 }
1591
Daniel Dunbarf0eddb82009-03-18 02:55:38 +00001592 const ToolChain &TC = C.getDefaultToolChain();
Chandler Carruth0ae39aa2013-07-30 17:57:09 +00001593
1594 if (C.getArgs().hasArg(options::OPT_v))
1595 TC.printVerboseInfo(llvm::errs());
1596
Meador Inge51208a32017-04-04 21:46:50 +00001597 if (C.getArgs().hasArg(options::OPT_print_resource_dir)) {
Meador Ingea9113952017-04-05 22:27:20 +00001598 llvm::outs() << ResourceDir << '\n';
Meador Inge51208a32017-04-04 21:46:50 +00001599 return false;
1600 }
1601
Daniel Dunbard972e222009-03-20 04:37:21 +00001602 if (C.getArgs().hasArg(options::OPT_print_search_dirs)) {
1603 llvm::outs() << "programs: =";
Douglas Katzman51fe7bf2015-06-23 22:43:50 +00001604 bool separator = false;
1605 for (const std::string &Path : TC.getProgramPaths()) {
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001606 if (separator)
1607 llvm::outs() << ':';
Douglas Katzman51fe7bf2015-06-23 22:43:50 +00001608 llvm::outs() << Path;
1609 separator = true;
Daniel Dunbard972e222009-03-20 04:37:21 +00001610 }
1611 llvm::outs() << "\n";
Peter Collingbournefa9771f2011-09-06 02:08:31 +00001612 llvm::outs() << "libraries: =" << ResourceDir;
Joerg Sonnenberger9c3e69b2011-07-16 10:50:05 +00001613
Sebastian Pop980920a2012-04-16 04:16:43 +00001614 StringRef sysroot = C.getSysRoot();
Joerg Sonnenberger9c3e69b2011-07-16 10:50:05 +00001615
Douglas Katzman51fe7bf2015-06-23 22:43:50 +00001616 for (const std::string &Path : TC.getFilePaths()) {
1617 // Always print a separator. ResourceDir was the first item shown.
Peter Collingbournefa9771f2011-09-06 02:08:31 +00001618 llvm::outs() << ':';
Douglas Katzman51fe7bf2015-06-23 22:43:50 +00001619 // Interpretation of leading '=' is needed only for NetBSD.
1620 if (Path[0] == '=')
Douglas Katzman26eabf62015-06-24 15:10:30 +00001621 llvm::outs() << sysroot << Path.substr(1);
Joerg Sonnenberger9c3e69b2011-07-16 10:50:05 +00001622 else
Douglas Katzman51fe7bf2015-06-23 22:43:50 +00001623 llvm::outs() << Path;
Daniel Dunbard972e222009-03-20 04:37:21 +00001624 }
1625 llvm::outs() << "\n";
Daniel Dunbar7c925282009-03-31 21:38:17 +00001626 return false;
Daniel Dunbard972e222009-03-20 04:37:21 +00001627 }
1628
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001629 // FIXME: The following handlers should use a callback mechanism, we don't
1630 // know what the client would like to do.
Daniel Dunbarf0eddb82009-03-18 02:55:38 +00001631 if (Arg *A = C.getArgs().getLastArg(options::OPT_print_file_name_EQ)) {
Richard Smithbd55daf2012-11-01 04:30:05 +00001632 llvm::outs() << GetFilePath(A->getValue(), TC) << "\n";
Daniel Dunbar5e0f6af2009-03-13 00:51:18 +00001633 return false;
1634 }
1635
Daniel Dunbarf0eddb82009-03-18 02:55:38 +00001636 if (Arg *A = C.getArgs().getLastArg(options::OPT_print_prog_name_EQ)) {
Saleem Abdulrasoole5f3cf82018-05-01 18:40:42 +00001637 StringRef ProgName = A->getValue();
1638
1639 // Null program name cannot have a path.
1640 if (! ProgName.empty())
1641 llvm::outs() << GetProgramPath(ProgName, TC);
1642
1643 llvm::outs() << "\n";
Daniel Dunbar5e0f6af2009-03-13 00:51:18 +00001644 return false;
1645 }
1646
Yuka Takahashic8068db2017-05-23 18:39:08 +00001647 if (Arg *A = C.getArgs().getLastArg(options::OPT_autocomplete)) {
Yuka Takahashiba5d4af2017-06-20 16:31:31 +00001648 StringRef PassedFlags = A->getValue();
Yuka Takahashi41789e42018-03-05 08:54:20 +00001649 HandleAutocompletions(PassedFlags);
Yuka Takahashic8068db2017-05-23 18:39:08 +00001650 return false;
1651 }
1652
Daniel Dunbarf0eddb82009-03-18 02:55:38 +00001653 if (C.getArgs().hasArg(options::OPT_print_libgcc_file_name)) {
Michal Gorny7cfe4802016-10-10 12:23:40 +00001654 ToolChain::RuntimeLibType RLT = TC.GetRuntimeLibType(C.getArgs());
Leo Li23bb21c2017-08-24 01:51:51 +00001655 const llvm::Triple Triple(TC.ComputeEffectiveClangTriple(C.getArgs()));
1656 RegisterEffectiveTriple TripleRAII(TC, Triple);
Michal Gorny7cfe4802016-10-10 12:23:40 +00001657 switch (RLT) {
1658 case ToolChain::RLT_CompilerRT:
1659 llvm::outs() << TC.getCompilerRT(C.getArgs(), "builtins") << "\n";
1660 break;
1661 case ToolChain::RLT_Libgcc:
1662 llvm::outs() << GetFilePath("libgcc.a", TC) << "\n";
1663 break;
1664 }
Daniel Dunbar5e0f6af2009-03-13 00:51:18 +00001665 return false;
1666 }
1667
Daniel Dunbar1b3ec3a2009-06-16 23:25:22 +00001668 if (C.getArgs().hasArg(options::OPT_print_multi_lib)) {
Douglas Katzmana34b7bf2015-06-30 19:32:57 +00001669 for (const Multilib &Multilib : TC.getMultilibs())
1670 llvm::outs() << Multilib << "\n";
Daniel Dunbar1b3ec3a2009-06-16 23:25:22 +00001671 return false;
1672 }
1673
Jonathan Roelofs2cea1be2014-02-12 03:21:20 +00001674 if (C.getArgs().hasArg(options::OPT_print_multi_directory)) {
Christian Bruel6ccc4a72018-09-06 14:03:44 +00001675 const Multilib &Multilib = TC.getMultilib();
1676 if (Multilib.gccSuffix().empty())
1677 llvm::outs() << ".\n";
1678 else {
1679 StringRef Suffix(Multilib.gccSuffix());
1680 assert(Suffix.front() == '/');
1681 llvm::outs() << Suffix.substr(1) << "\n";
Jonathan Roelofs3fa96d82014-02-12 01:36:51 +00001682 }
Jonathan Roelofs0e7ec602014-02-12 01:29:25 +00001683 return false;
1684 }
Petr Hosekbc86a992018-08-16 00:22:03 +00001685
1686 if (C.getArgs().hasArg(options::OPT_print_target_triple)) {
1687 llvm::outs() << TC.getTripleString() << "\n";
1688 return false;
1689 }
1690
1691 if (C.getArgs().hasArg(options::OPT_print_effective_triple)) {
1692 const llvm::Triple Triple(TC.ComputeEffectiveClangTriple(C.getArgs()));
1693 llvm::outs() << Triple.getTriple() << "\n";
1694 return false;
1695 }
1696
Daniel Dunbar5e0f6af2009-03-13 00:51:18 +00001697 return true;
1698}
1699
Douglas Katzmanfd528672015-06-11 15:05:22 +00001700// Display an action graph human-readably. Action A is the "sink" node
1701// and latest-occuring action. Traversal is in pre-order, visiting the
1702// inputs to each action before printing the action itself.
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001703static unsigned PrintActions1(const Compilation &C, Action *A,
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001704 std::map<Action *, unsigned> &Ids) {
Douglas Katzmanfd528672015-06-11 15:05:22 +00001705 if (Ids.count(A)) // A was already visited.
Daniel Dunbaraaf1ea62009-03-13 12:19:02 +00001706 return Ids[A];
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001707
Daniel Dunbaraaf1ea62009-03-13 12:19:02 +00001708 std::string str;
1709 llvm::raw_string_ostream os(str);
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001710
Daniel Dunbaraaf1ea62009-03-13 12:19:02 +00001711 os << Action::getClassName(A->getKind()) << ", ";
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001712 if (InputAction *IA = dyn_cast<InputAction>(A)) {
Richard Smithbd55daf2012-11-01 04:30:05 +00001713 os << "\"" << IA->getInputArg().getValue() << "\"";
Daniel Dunbaraaf1ea62009-03-13 12:19:02 +00001714 } else if (BindArchAction *BIA = dyn_cast<BindArchAction>(A)) {
Douglas Katzmanb7e8ef02015-06-25 19:37:41 +00001715 os << '"' << BIA->getArchName() << '"' << ", {"
Nico Weber5a459f82016-02-23 19:30:43 +00001716 << PrintActions1(C, *BIA->input_begin(), Ids) << "}";
Samuel Antaod06239d2016-07-15 23:13:27 +00001717 } else if (OffloadAction *OA = dyn_cast<OffloadAction>(A)) {
1718 bool IsFirst = true;
1719 OA->doOnEachDependence(
1720 [&](Action *A, const ToolChain *TC, const char *BoundArch) {
1721 // E.g. for two CUDA device dependences whose bound arch is sm_20 and
1722 // sm_35 this will generate:
1723 // "cuda-device" (nvptx64-nvidia-cuda:sm_20) {#ID}, "cuda-device"
1724 // (nvptx64-nvidia-cuda:sm_35) {#ID}
1725 if (!IsFirst)
1726 os << ", ";
1727 os << '"';
1728 if (TC)
1729 os << A->getOffloadingKindPrefix();
1730 else
1731 os << "host";
1732 os << " (";
1733 os << TC->getTriple().normalize();
1734
1735 if (BoundArch)
1736 os << ":" << BoundArch;
1737 os << ")";
1738 os << '"';
1739 os << " {" << PrintActions1(C, A, Ids) << "}";
1740 IsFirst = false;
1741 });
Daniel Dunbaraaf1ea62009-03-13 12:19:02 +00001742 } else {
Samuel Antaod06239d2016-07-15 23:13:27 +00001743 const ActionList *AL = &A->getInputs();
Artem Belevich0ff05cd2015-07-13 23:27:56 +00001744
Artem Belevich23256752015-09-22 17:23:09 +00001745 if (AL->size()) {
1746 const char *Prefix = "{";
1747 for (Action *PreRequisite : *AL) {
1748 os << Prefix << PrintActions1(C, PreRequisite, Ids);
1749 Prefix = ", ";
1750 }
1751 os << "}";
1752 } else
1753 os << "{}";
Daniel Dunbaraaf1ea62009-03-13 12:19:02 +00001754 }
1755
Samuel Antaod06239d2016-07-15 23:13:27 +00001756 // Append offload info for all options other than the offloading action
1757 // itself (e.g. (cuda-device, sm_20) or (cuda-host)).
1758 std::string offload_str;
1759 llvm::raw_string_ostream offload_os(offload_str);
1760 if (!isa<OffloadAction>(A)) {
1761 auto S = A->getOffloadingKindPrefix();
1762 if (!S.empty()) {
1763 offload_os << ", (" << S;
1764 if (A->getOffloadingArch())
1765 offload_os << ", " << A->getOffloadingArch();
1766 offload_os << ")";
1767 }
1768 }
1769
Daniel Dunbaraaf1ea62009-03-13 12:19:02 +00001770 unsigned Id = Ids.size();
1771 Ids[A] = Id;
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001772 llvm::errs() << Id << ": " << os.str() << ", "
Samuel Antaod06239d2016-07-15 23:13:27 +00001773 << types::getTypeName(A->getType()) << offload_os.str() << "\n";
Daniel Dunbaraaf1ea62009-03-13 12:19:02 +00001774
1775 return Id;
1776}
1777
Douglas Katzmanfd528672015-06-11 15:05:22 +00001778// Print the action graphs in a compilation C.
1779// For example "clang -c file1.c file2.c" is composed of two subgraphs.
Daniel Dunbareb843be2009-03-18 03:13:20 +00001780void Driver::PrintActions(const Compilation &C) const {
Douglas Katzmanb7e8ef02015-06-25 19:37:41 +00001781 std::map<Action *, unsigned> Ids;
1782 for (Action *A : C.getActions())
1783 PrintActions1(C, A, Ids);
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00001784}
1785
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001786/// Check whether the given input tree contains any compilation or
Joerg Sonnenberger5fe4a7d2011-05-06 14:05:11 +00001787/// assembly actions.
1788static bool ContainsCompileOrAssembleAction(const Action *A) {
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001789 if (isa<CompileJobAction>(A) || isa<BackendJobAction>(A) ||
Bob Wilson23a55f12014-12-21 07:00:00 +00001790 isa<AssembleJobAction>(A))
Daniel Dunbar00d3d8e2010-06-29 16:38:33 +00001791 return true;
1792
Nico Weber5a459f82016-02-23 19:30:43 +00001793 for (const Action *Input : A->inputs())
Nico Weberfb80f962015-09-19 21:36:51 +00001794 if (ContainsCompileOrAssembleAction(Input))
Daniel Dunbar00d3d8e2010-06-29 16:38:33 +00001795 return true;
1796
1797 return false;
1798}
1799
Artem Belevich5e2a3ec2015-11-17 22:28:40 +00001800void Driver::BuildUniversalActions(Compilation &C, const ToolChain &TC,
1801 const InputList &BAInputs) const {
1802 DerivedArgList &Args = C.getArgs();
1803 ActionList &Actions = C.getActions();
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001804 llvm::PrettyStackTraceString CrashInfo("Building universal build actions");
1805 // Collect the list of architectures. Duplicates are allowed, but should only
1806 // be handled once (in the order seen).
Daniel Dunbare5dc4822009-03-13 20:33:35 +00001807 llvm::StringSet<> ArchNames;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001808 SmallVector<const char *, 4> Archs;
Saleem Abdulrasool688b6bc2014-12-29 19:01:36 +00001809 for (Arg *A : Args) {
Daniel Dunbar0bfb21e2009-11-19 03:26:40 +00001810 if (A->getOption().matches(options::OPT_arch)) {
Daniel Dunbar9c3f7c42009-09-08 23:37:30 +00001811 // Validate the option here; we don't save the type here because its
1812 // particular spelling may participate in other driver choices.
1813 llvm::Triple::ArchType Arch =
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001814 tools::darwin::getArchTypeForMachOArchName(A->getValue());
Daniel Dunbar9c3f7c42009-09-08 23:37:30 +00001815 if (Arch == llvm::Triple::UnknownArch) {
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001816 Diag(clang::diag::err_drv_invalid_arch_name) << A->getAsString(Args);
Daniel Dunbar9c3f7c42009-09-08 23:37:30 +00001817 continue;
1818 }
1819
Daniel Dunbar2da02722009-03-19 07:55:12 +00001820 A->claim();
David Blaikie61b86d42014-11-19 02:56:13 +00001821 if (ArchNames.insert(A->getValue()).second)
Richard Smithbd55daf2012-11-01 04:30:05 +00001822 Archs.push_back(A->getValue());
Daniel Dunbarf479c122009-03-12 18:40:18 +00001823 }
1824 }
1825
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001826 // When there is no explicit arch for this platform, make sure we still bind
1827 // the architecture (to the default) so that -Xarch_ is handled correctly.
Daniel Dunbareb843be2009-03-18 03:13:20 +00001828 if (!Archs.size())
Daniel Dunbarc3bd9f52012-11-08 03:38:26 +00001829 Archs.push_back(Args.MakeArgString(TC.getDefaultUniversalArchName()));
Daniel Dunbarf479c122009-03-12 18:40:18 +00001830
Daniel Dunbarf479c122009-03-12 18:40:18 +00001831 ActionList SingleActions;
Justin Lebar0f3474c2016-02-11 02:00:50 +00001832 BuildActions(C, Args, BAInputs, SingleActions);
Daniel Dunbarf479c122009-03-12 18:40:18 +00001833
Daniel Dunbar6beaf512010-06-04 18:28:41 +00001834 // Add in arch bindings for every top level action, as well as lipo and
1835 // dsymutil steps if needed.
Nico Weberfb80f962015-09-19 21:36:51 +00001836 for (Action* Act : SingleActions) {
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001837 // Make sure we can lipo this kind of output. If not (and it is an actual
1838 // output) then we disallow, since we can't create an output file with the
1839 // right name without overwriting it. We could remove this oddity by just
1840 // changing the output names to include the arch, which would also fix
Daniel Dunbarf479c122009-03-12 18:40:18 +00001841 // -save-temps. Compatibility wins for now.
1842
Daniel Dunbare2ca3bd2009-03-13 17:46:02 +00001843 if (Archs.size() > 1 && !types::canLipoType(Act->getType()))
Daniel Dunbarf479c122009-03-12 18:40:18 +00001844 Diag(clang::diag::err_drv_invalid_output_with_multiple_archs)
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001845 << types::getTypeName(Act->getType());
Daniel Dunbarf479c122009-03-12 18:40:18 +00001846
1847 ActionList Inputs;
Justin Lebar41094612016-01-11 23:07:27 +00001848 for (unsigned i = 0, e = Archs.size(); i != e; ++i)
1849 Inputs.push_back(C.MakeAction<BindArchAction>(Act, Archs[i]));
Daniel Dunbarf479c122009-03-12 18:40:18 +00001850
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001851 // Lipo if necessary, we do it this way because we need to set the arch flag
1852 // so that -Xarch_ gets overwritten.
Daniel Dunbarf479c122009-03-12 18:40:18 +00001853 if (Inputs.size() == 1 || Act->getType() == types::TY_Nothing)
1854 Actions.append(Inputs.begin(), Inputs.end());
1855 else
Justin Lebar41094612016-01-11 23:07:27 +00001856 Actions.push_back(C.MakeAction<LipoJobAction>(Inputs, Act->getType()));
Daniel Dunbar6beaf512010-06-04 18:28:41 +00001857
Eric Christopher65c05fa2012-02-06 19:43:51 +00001858 // Handle debug info queries.
1859 Arg *A = Args.getLastArg(options::OPT_g_Group);
David Blaikie6f9f4eb2012-04-15 21:22:10 +00001860 if (A && !A->getOption().matches(options::OPT_g0) &&
1861 !A->getOption().matches(options::OPT_gstabs) &&
1862 ContainsCompileOrAssembleAction(Actions.back())) {
Chad Rosier62135492012-07-09 17:31:28 +00001863
David Blaikie6f9f4eb2012-04-15 21:22:10 +00001864 // Add a 'dsymutil' step if necessary, when debug info is enabled and we
1865 // have a compile input. We need to run 'dsymutil' ourselves in such cases
Eric Christopher776c26f2013-01-28 17:39:03 +00001866 // because the debug info will refer to a temporary object file which
David Blaikie6f9f4eb2012-04-15 21:22:10 +00001867 // will be removed at the end of the compilation process.
1868 if (Act->getType() == types::TY_Image) {
1869 ActionList Inputs;
1870 Inputs.push_back(Actions.back());
1871 Actions.pop_back();
Justin Lebar41094612016-01-11 23:07:27 +00001872 Actions.push_back(
1873 C.MakeAction<DsymutilJobAction>(Inputs, types::TY_dSYM));
Daniel Dunbar6beaf512010-06-04 18:28:41 +00001874 }
David Blaikie6f9f4eb2012-04-15 21:22:10 +00001875
Ben Langmuir9b9a8d32014-02-06 18:53:25 +00001876 // Verify the debug info output.
Alp Tokere9d2bfc2014-01-17 02:06:23 +00001877 if (Args.hasArg(options::OPT_verify_debug_info)) {
Justin Lebar41094612016-01-11 23:07:27 +00001878 Action* LastAction = Actions.back();
David Blaikie6f9f4eb2012-04-15 21:22:10 +00001879 Actions.pop_back();
Justin Lebar41094612016-01-11 23:07:27 +00001880 Actions.push_back(C.MakeAction<VerifyDebugInfoJobAction>(
1881 LastAction, types::TY_Nothing));
David Blaikie6f9f4eb2012-04-15 21:22:10 +00001882 }
1883 }
Daniel Dunbarf479c122009-03-12 18:40:18 +00001884 }
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00001885}
1886
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001887/// Check that the file referenced by Value exists. If it doesn't,
Hans Wennborg6ee64d52013-08-06 00:20:31 +00001888/// issue a diagnostic and return false.
Alp Toker8c8a8752013-12-03 06:53:35 +00001889static bool DiagnoseInputExistence(const Driver &D, const DerivedArgList &Args,
Hans Wennborg12f4f8b2016-04-15 01:12:32 +00001890 StringRef Value, types::ID Ty) {
Hans Wennborg6ee64d52013-08-06 00:20:31 +00001891 if (!D.getCheckInputsExist())
1892 return true;
1893
1894 // stdin always exists.
1895 if (Value == "-")
1896 return true;
1897
1898 SmallString<64> Path(Value);
1899 if (Arg *WorkDir = Args.getLastArg(options::OPT_working_directory)) {
Yaron Keren92e1b622015-03-18 10:17:07 +00001900 if (!llvm::sys::path::is_absolute(Path)) {
Hans Wennborg6ee64d52013-08-06 00:20:31 +00001901 SmallString<64> Directory(WorkDir->getValue());
1902 llvm::sys::path::append(Directory, Value);
1903 Path.assign(Directory);
1904 }
1905 }
1906
1907 if (llvm::sys::fs::exists(Twine(Path)))
1908 return true;
1909
Hans Wennborg12f4f8b2016-04-15 01:12:32 +00001910 if (D.IsCLMode()) {
1911 if (!llvm::sys::path::is_absolute(Twine(Path)) &&
1912 llvm::sys::Process::FindInEnvPath("LIB", Value))
1913 return true;
1914
1915 if (Args.hasArg(options::OPT__SLASH_link) && Ty == types::TY_Object) {
1916 // Arguments to the /link flag might cause the linker to search for object
1917 // and library files in paths we don't know about. Don't error in such
1918 // cases.
1919 return true;
1920 }
1921 }
Hans Wennborg23d26a32014-06-18 17:21:50 +00001922
Yaron Keren92e1b622015-03-18 10:17:07 +00001923 D.Diag(clang::diag::err_drv_no_such_file) << Path;
Hans Wennborg6ee64d52013-08-06 00:20:31 +00001924 return false;
1925}
1926
Chad Rosierecdede82011-08-12 22:08:57 +00001927// Construct a the list of inputs and their types.
Hans Wennborg55362852014-05-02 22:55:30 +00001928void Driver::BuildInputs(const ToolChain &TC, DerivedArgList &Args,
Chad Rosierecdede82011-08-12 22:08:57 +00001929 InputList &Inputs) const {
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001930 // Track the current user specified (-x) input. We also explicitly track the
1931 // argument used to set the type; we only want to claim the type when we
1932 // actually use it, so we warn about unused -x arguments.
Daniel Dunbarc5a5ac52009-03-13 17:57:10 +00001933 types::ID InputType = types::TY_Nothing;
Craig Topper92fc2df2014-05-17 16:56:41 +00001934 Arg *InputTypeArg = nullptr;
Daniel Dunbarc5a5ac52009-03-13 17:57:10 +00001935
Hans Wennborg0d0b19c2013-08-12 18:34:17 +00001936 // The last /TC or /TP option sets the input type to C or C++ globally.
Ehsan Akhgaric249abb2014-09-12 21:44:24 +00001937 if (Arg *TCTP = Args.getLastArgNoClaim(options::OPT__SLASH_TC,
1938 options::OPT__SLASH_TP)) {
Hans Wennborg6ee64d52013-08-06 00:20:31 +00001939 InputTypeArg = TCTP;
Hans Wennborg0d0b19c2013-08-12 18:34:17 +00001940 InputType = TCTP->getOption().matches(options::OPT__SLASH_TC)
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001941 ? types::TY_C
1942 : types::TY_CXX;
Hans Wennborg6ee64d52013-08-06 00:20:31 +00001943
Richard Smith0aef3052017-02-18 01:14:43 +00001944 Arg *Previous = nullptr;
Hans Wennborg0d0b19c2013-08-12 18:34:17 +00001945 bool ShowNote = false;
Richard Smith0aef3052017-02-18 01:14:43 +00001946 for (Arg *A : Args.filtered(options::OPT__SLASH_TC, options::OPT__SLASH_TP)) {
1947 if (Previous) {
1948 Diag(clang::diag::warn_drv_overriding_flag_option)
1949 << Previous->getSpelling() << A->getSpelling();
1950 ShowNote = true;
1951 }
1952 Previous = A;
Hans Wennborg6ee64d52013-08-06 00:20:31 +00001953 }
Hans Wennborg0d0b19c2013-08-12 18:34:17 +00001954 if (ShowNote)
1955 Diag(clang::diag::note_drv_t_option_is_global);
Hans Wennborg6ee64d52013-08-06 00:20:31 +00001956
1957 // No driver mode exposes -x and /TC or /TP; we don't support mixing them.
1958 assert(!Args.hasArg(options::OPT_x) && "-x and /TC or /TP is not allowed");
1959 }
1960
Saleem Abdulrasool688b6bc2014-12-29 19:01:36 +00001961 for (Arg *A : Args) {
Michael J. Spencerad3ccc32012-08-20 21:41:17 +00001962 if (A->getOption().getKind() == Option::InputClass) {
Richard Smithbd55daf2012-11-01 04:30:05 +00001963 const char *Value = A->getValue();
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00001964 types::ID Ty = types::TY_INVALID;
1965
1966 // Infer the input type if necessary.
Daniel Dunbarc5a5ac52009-03-13 17:57:10 +00001967 if (InputType == types::TY_Nothing) {
1968 // If there was an explicit arg for this, claim it.
1969 if (InputTypeArg)
1970 InputTypeArg->claim();
1971
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00001972 // stdin must be handled specially.
1973 if (memcmp(Value, "-", 2) == 0) {
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001974 // If running with -E, treat as a C input (this changes the builtin
1975 // macros, for example). This may be overridden by -ObjC below.
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00001976 //
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001977 // Otherwise emit an error but still use a valid type to avoid
1978 // spurious errors (e.g., no inputs).
Hans Wennborg70850d82013-07-18 20:29:38 +00001979 if (!Args.hasArgNoClaim(options::OPT_E) && !CCCIsCPP())
Hans Wennborgcfdd8b52014-01-29 01:04:40 +00001980 Diag(IsCLMode() ? clang::diag::err_drv_unknown_stdin_type_clang_cl
1981 : clang::diag::err_drv_unknown_stdin_type);
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00001982 Ty = types::TY_C;
1983 } else {
Joerg Sonnenbergerbdbdf702011-03-16 22:45:02 +00001984 // Otherwise lookup by extension.
1985 // Fallback is C if invoked as C preprocessor or Object otherwise.
1986 // We use a host hook here because Darwin at least has its own
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001987 // idea of what .s is.
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00001988 if (const char *Ext = strrchr(Value, '.'))
Daniel Dunbarcc7df6c2010-08-02 05:43:56 +00001989 Ty = TC.LookupTypeForExtension(Ext + 1);
Daniel Dunbarea9f0322009-03-20 23:39:23 +00001990
Joerg Sonnenbergerbdbdf702011-03-16 22:45:02 +00001991 if (Ty == types::TY_INVALID) {
Hans Wennborg70850d82013-07-18 20:29:38 +00001992 if (CCCIsCPP())
Joerg Sonnenbergerbdbdf702011-03-16 22:45:02 +00001993 Ty = types::TY_C;
1994 else
1995 Ty = types::TY_Object;
1996 }
Daniel Dunbar0ac94452010-02-17 20:32:58 +00001997
1998 // If the driver is invoked as C++ compiler (like clang++ or c++) it
1999 // should autodetect some input files as C++ for g++ compatibility.
Hans Wennborg70850d82013-07-18 20:29:38 +00002000 if (CCCIsCXX()) {
Daniel Dunbar0ac94452010-02-17 20:32:58 +00002001 types::ID OldTy = Ty;
2002 Ty = types::lookupCXXTypeForCType(Ty);
2003
2004 if (Ty != OldTy)
2005 Diag(clang::diag::warn_drv_treating_input_as_cxx)
Douglas Katzmana67e50c2015-06-26 15:47:46 +00002006 << getTypeName(OldTy) << getTypeName(Ty);
Daniel Dunbar0ac94452010-02-17 20:32:58 +00002007 }
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00002008 }
2009
Daniel Dunbar82b22102009-05-18 21:47:54 +00002010 // -ObjC and -ObjC++ override the default language, but only for "source
2011 // files". We just treat everything that isn't a linker input as a
2012 // source file.
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00002013 //
Daniel Dunbar82b22102009-05-18 21:47:54 +00002014 // FIXME: Clean this up if we move the phase sequence into the type.
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00002015 if (Ty != types::TY_Object) {
2016 if (Args.hasArg(options::OPT_ObjC))
2017 Ty = types::TY_ObjC;
2018 else if (Args.hasArg(options::OPT_ObjCXX))
2019 Ty = types::TY_ObjCXX;
2020 }
2021 } else {
2022 assert(InputTypeArg && "InputType set w/o InputTypeArg");
Ehsan Akhgari7e954ea2014-09-12 18:15:10 +00002023 if (!InputTypeArg->getOption().matches(options::OPT_x)) {
2024 // If emulating cl.exe, make sure that /TC and /TP don't affect input
2025 // object files.
2026 const char *Ext = strrchr(Value, '.');
2027 if (Ext && TC.LookupTypeForExtension(Ext + 1) == types::TY_Object)
2028 Ty = types::TY_Object;
2029 }
2030 if (Ty == types::TY_INVALID) {
2031 Ty = InputType;
2032 InputTypeArg->claim();
2033 }
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00002034 }
2035
Hans Wennborg12f4f8b2016-04-15 01:12:32 +00002036 if (DiagnoseInputExistence(*this, Args, Value, Ty))
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00002037 Inputs.push_back(std::make_pair(Ty, A));
2038
Hans Wennborg6ee64d52013-08-06 00:20:31 +00002039 } else if (A->getOption().matches(options::OPT__SLASH_Tc)) {
2040 StringRef Value = A->getValue();
Hans Wennborg12f4f8b2016-04-15 01:12:32 +00002041 if (DiagnoseInputExistence(*this, Args, Value, types::TY_C)) {
David Blaikie0aaa7622017-01-13 17:34:15 +00002042 Arg *InputArg = MakeInputArg(Args, *Opts, A->getValue());
Hans Wennborg6ee64d52013-08-06 00:20:31 +00002043 Inputs.push_back(std::make_pair(types::TY_C, InputArg));
2044 }
2045 A->claim();
2046 } else if (A->getOption().matches(options::OPT__SLASH_Tp)) {
2047 StringRef Value = A->getValue();
Hans Wennborg12f4f8b2016-04-15 01:12:32 +00002048 if (DiagnoseInputExistence(*this, Args, Value, types::TY_CXX)) {
David Blaikie0aaa7622017-01-13 17:34:15 +00002049 Arg *InputArg = MakeInputArg(Args, *Opts, A->getValue());
Hans Wennborg6ee64d52013-08-06 00:20:31 +00002050 Inputs.push_back(std::make_pair(types::TY_CXX, InputArg));
2051 }
2052 A->claim();
Michael J. Spencer66e2b202012-10-19 22:37:06 +00002053 } else if (A->getOption().hasFlag(options::LinkerInput)) {
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00002054 // Just treat as object type, we could make a special type for this if
2055 // necessary.
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00002056 Inputs.push_back(std::make_pair(types::TY_Object, A));
2057
Daniel Dunbar0bfb21e2009-11-19 03:26:40 +00002058 } else if (A->getOption().matches(options::OPT_x)) {
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00002059 InputTypeArg = A;
Richard Smithbd55daf2012-11-01 04:30:05 +00002060 InputType = types::lookupTypeForTypeSpecifier(A->getValue());
Chad Rosier706c2352012-04-07 00:01:31 +00002061 A->claim();
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00002062
2063 // Follow gcc behavior and treat as linker input for invalid -x
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00002064 // options. Its not clear why we shouldn't just revert to unknown; but
Michael J. Spencer1a4fe8c2010-12-17 21:22:33 +00002065 // this isn't very important, we might as well be bug compatible.
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00002066 if (!InputType) {
Richard Smithbd55daf2012-11-01 04:30:05 +00002067 Diag(clang::diag::err_drv_unknown_language) << A->getValue();
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00002068 InputType = types::TY_Object;
2069 }
Hans Wennborg091f1b62017-01-27 17:09:41 +00002070 } else if (A->getOption().getID() == options::OPT__SLASH_U) {
2071 assert(A->getNumValues() == 1 && "The /U option has one value.");
2072 StringRef Val = A->getValue(0);
2073 if (Val.find_first_of("/\\") != StringRef::npos) {
2074 // Warn about e.g. "/Users/me/myfile.c".
2075 Diag(diag::warn_slash_u_filename) << Val;
2076 Diag(diag::note_use_dashdash);
2077 }
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00002078 }
2079 }
Hans Wennborg70850d82013-07-18 20:29:38 +00002080 if (CCCIsCPP() && Inputs.empty()) {
Joerg Sonnenbergerb86f5f42011-03-06 23:31:01 +00002081 // If called as standalone preprocessor, stdin is processed
2082 // if no other input is present.
David Blaikie0aaa7622017-01-13 17:34:15 +00002083 Arg *A = MakeInputArg(Args, *Opts, "-");
Joerg Sonnenbergerb86f5f42011-03-06 23:31:01 +00002084 Inputs.push_back(std::make_pair(types::TY_C, A));
2085 }
Chad Rosierecdede82011-08-12 22:08:57 +00002086}
2087
Samuel Antao64e965e2016-09-30 15:34:19 +00002088namespace {
2089/// Provides a convenient interface for different programming models to generate
2090/// the required device actions.
2091class OffloadingActionBuilder final {
2092 /// Flag used to trace errors in the builder.
2093 bool IsValid = false;
2094
2095 /// The compilation that is using this builder.
2096 Compilation &C;
2097
Samuel Antao64e965e2016-09-30 15:34:19 +00002098 /// Map between an input argument and the offload kinds used to process it.
2099 std::map<const Arg *, unsigned> InputArgToOffloadKindMap;
2100
2101 /// Builder interface. It doesn't build anything or keep any state.
2102 class DeviceActionBuilder {
2103 public:
2104 typedef llvm::SmallVector<phases::ID, phases::MaxNumberOfPhases> PhasesTy;
2105
2106 enum ActionBuilderReturnCode {
2107 // The builder acted successfully on the current action.
2108 ABRT_Success,
2109 // The builder didn't have to act on the current action.
2110 ABRT_Inactive,
2111 // The builder was successful and requested the host action to not be
2112 // generated.
2113 ABRT_Ignore_Host,
2114 };
2115
2116 protected:
2117 /// Compilation associated with this builder.
2118 Compilation &C;
2119
2120 /// Tool chains associated with this builder. The same programming
2121 /// model may have associated one or more tool chains.
2122 SmallVector<const ToolChain *, 2> ToolChains;
2123
2124 /// The derived arguments associated with this builder.
2125 DerivedArgList &Args;
2126
2127 /// The inputs associated with this builder.
2128 const Driver::InputList &Inputs;
2129
2130 /// The associated offload kind.
2131 Action::OffloadKind AssociatedOffloadKind = Action::OFK_None;
2132
2133 public:
2134 DeviceActionBuilder(Compilation &C, DerivedArgList &Args,
2135 const Driver::InputList &Inputs,
2136 Action::OffloadKind AssociatedOffloadKind)
2137 : C(C), Args(Args), Inputs(Inputs),
2138 AssociatedOffloadKind(AssociatedOffloadKind) {}
2139 virtual ~DeviceActionBuilder() {}
2140
2141 /// Fill up the array \a DA with all the device dependences that should be
2142 /// added to the provided host action \a HostAction. By default it is
2143 /// inactive.
2144 virtual ActionBuilderReturnCode
Samuel Antao28c4f182016-10-27 17:08:03 +00002145 getDeviceDependences(OffloadAction::DeviceDependences &DA,
2146 phases::ID CurPhase, phases::ID FinalPhase,
2147 PhasesTy &Phases) {
Samuel Antao64e965e2016-09-30 15:34:19 +00002148 return ABRT_Inactive;
2149 }
2150
2151 /// Update the state to include the provided host action \a HostAction as a
2152 /// dependency of the current device action. By default it is inactive.
2153 virtual ActionBuilderReturnCode addDeviceDepences(Action *HostAction) {
2154 return ABRT_Inactive;
2155 }
2156
2157 /// Append top level actions generated by the builder. Return true if errors
2158 /// were found.
2159 virtual void appendTopLevelActions(ActionList &AL) {}
2160
2161 /// Append linker actions generated by the builder. Return true if errors
2162 /// were found.
2163 virtual void appendLinkDependences(OffloadAction::DeviceDependences &DA) {}
2164
2165 /// Initialize the builder. Return true if any initialization errors are
2166 /// found.
2167 virtual bool initialize() { return false; }
2168
Samuel Antao69d6f312016-10-27 17:50:43 +00002169 /// Return true if the builder can use bundling/unbundling.
2170 virtual bool canUseBundlerUnbundler() const { return false; }
2171
Samuel Antao64e965e2016-09-30 15:34:19 +00002172 /// Return true if this builder is valid. We have a valid builder if we have
2173 /// associated device tool chains.
2174 bool isValid() { return !ToolChains.empty(); }
2175
2176 /// Return the associated offload kind.
2177 Action::OffloadKind getAssociatedOffloadKind() {
2178 return AssociatedOffloadKind;
2179 }
2180 };
2181
Yaxun Liu3af038b2018-05-30 00:49:10 +00002182 /// Base class for CUDA/HIP action builder. It injects device code in
2183 /// the host backend action.
2184 class CudaActionBuilderBase : public DeviceActionBuilder {
2185 protected:
Samuel Antao64e965e2016-09-30 15:34:19 +00002186 /// Flags to signal if the user requested host-only or device-only
2187 /// compilation.
2188 bool CompileHostOnly = false;
2189 bool CompileDeviceOnly = false;
2190
2191 /// List of GPU architectures to use in this compilation.
2192 SmallVector<CudaArch, 4> GpuArchList;
2193
2194 /// The CUDA actions for the current input.
2195 ActionList CudaDeviceActions;
2196
2197 /// The CUDA fat binary if it was generated for the current input.
2198 Action *CudaFatBinary = nullptr;
2199
2200 /// Flag that is set to true if this builder acted on the current input.
2201 bool IsActive = false;
Yaxun Liu3af038b2018-05-30 00:49:10 +00002202 public:
2203 CudaActionBuilderBase(Compilation &C, DerivedArgList &Args,
2204 const Driver::InputList &Inputs,
2205 Action::OffloadKind OFKind)
2206 : DeviceActionBuilder(C, Args, Inputs, OFKind) {}
Samuel Antao64e965e2016-09-30 15:34:19 +00002207
Yaxun Liu3af038b2018-05-30 00:49:10 +00002208 ActionBuilderReturnCode addDeviceDepences(Action *HostAction) override {
2209 // While generating code for CUDA, we only depend on the host input action
2210 // to trigger the creation of all the CUDA device actions.
2211
2212 // If we are dealing with an input action, replicate it for each GPU
2213 // architecture. If we are in host-only mode we return 'success' so that
2214 // the host uses the CUDA offload kind.
2215 if (auto *IA = dyn_cast<InputAction>(HostAction)) {
2216 assert(!GpuArchList.empty() &&
2217 "We should have at least one GPU architecture.");
2218
2219 // If the host input is not CUDA or HIP, we don't need to bother about
2220 // this input.
2221 if (IA->getType() != types::TY_CUDA &&
2222 IA->getType() != types::TY_HIP) {
2223 // The builder will ignore this input.
2224 IsActive = false;
2225 return ABRT_Inactive;
2226 }
2227
2228 // Set the flag to true, so that the builder acts on the current input.
2229 IsActive = true;
2230
2231 if (CompileHostOnly)
2232 return ABRT_Success;
2233
2234 // Replicate inputs for each GPU architecture.
2235 auto Ty = IA->getType() == types::TY_HIP ? types::TY_HIP_DEVICE
2236 : types::TY_CUDA_DEVICE;
2237 for (unsigned I = 0, E = GpuArchList.size(); I != E; ++I) {
2238 CudaDeviceActions.push_back(
2239 C.MakeAction<InputAction>(IA->getInputArg(), Ty));
2240 }
2241
2242 return ABRT_Success;
2243 }
2244
2245 // If this is an unbundling action use it as is for each CUDA toolchain.
2246 if (auto *UA = dyn_cast<OffloadUnbundlingJobAction>(HostAction)) {
2247 CudaDeviceActions.clear();
2248 for (auto Arch : GpuArchList) {
2249 CudaDeviceActions.push_back(UA);
2250 UA->registerDependentActionInfo(ToolChains[0], CudaArchToString(Arch),
2251 AssociatedOffloadKind);
2252 }
2253 return ABRT_Success;
2254 }
2255
2256 return IsActive ? ABRT_Success : ABRT_Inactive;
2257 }
2258
2259 void appendTopLevelActions(ActionList &AL) override {
2260 // Utility to append actions to the top level list.
2261 auto AddTopLevel = [&](Action *A, CudaArch BoundArch) {
2262 OffloadAction::DeviceDependences Dep;
2263 Dep.add(*A, *ToolChains.front(), CudaArchToString(BoundArch),
2264 AssociatedOffloadKind);
2265 AL.push_back(C.MakeAction<OffloadAction>(Dep, A->getType()));
2266 };
2267
2268 // If we have a fat binary, add it to the list.
2269 if (CudaFatBinary) {
2270 AddTopLevel(CudaFatBinary, CudaArch::UNKNOWN);
2271 CudaDeviceActions.clear();
2272 CudaFatBinary = nullptr;
2273 return;
2274 }
2275
2276 if (CudaDeviceActions.empty())
2277 return;
2278
2279 // If we have CUDA actions at this point, that's because we have a have
2280 // partial compilation, so we should have an action for each GPU
2281 // architecture.
2282 assert(CudaDeviceActions.size() == GpuArchList.size() &&
2283 "Expecting one action per GPU architecture.");
2284 assert(ToolChains.size() == 1 &&
2285 "Expecting to have a sing CUDA toolchain.");
2286 for (unsigned I = 0, E = GpuArchList.size(); I != E; ++I)
2287 AddTopLevel(CudaDeviceActions[I], GpuArchList[I]);
2288
2289 CudaDeviceActions.clear();
2290 }
2291
2292 bool initialize() override {
2293 assert(AssociatedOffloadKind == Action::OFK_Cuda ||
2294 AssociatedOffloadKind == Action::OFK_HIP);
2295
2296 // We don't need to support CUDA.
2297 if (AssociatedOffloadKind == Action::OFK_Cuda &&
2298 !C.hasOffloadToolChain<Action::OFK_Cuda>())
2299 return false;
2300
2301 // We don't need to support HIP.
2302 if (AssociatedOffloadKind == Action::OFK_HIP &&
2303 !C.hasOffloadToolChain<Action::OFK_HIP>())
2304 return false;
2305
2306 const ToolChain *HostTC = C.getSingleOffloadToolChain<Action::OFK_Host>();
2307 assert(HostTC && "No toolchain for host compilation.");
2308 if (HostTC->getTriple().isNVPTX() ||
2309 HostTC->getTriple().getArch() == llvm::Triple::amdgcn) {
2310 // We do not support targeting NVPTX/AMDGCN for host compilation. Throw
2311 // an error and abort pipeline construction early so we don't trip
2312 // asserts that assume device-side compilation.
2313 C.getDriver().Diag(diag::err_drv_cuda_host_arch)
2314 << HostTC->getTriple().getArchName();
2315 return true;
2316 }
2317
2318 ToolChains.push_back(
2319 AssociatedOffloadKind == Action::OFK_Cuda
2320 ? C.getSingleOffloadToolChain<Action::OFK_Cuda>()
2321 : C.getSingleOffloadToolChain<Action::OFK_HIP>());
2322
2323 Arg *PartialCompilationArg = Args.getLastArg(
2324 options::OPT_cuda_host_only, options::OPT_cuda_device_only,
2325 options::OPT_cuda_compile_host_device);
2326 CompileHostOnly = PartialCompilationArg &&
2327 PartialCompilationArg->getOption().matches(
2328 options::OPT_cuda_host_only);
2329 CompileDeviceOnly = PartialCompilationArg &&
2330 PartialCompilationArg->getOption().matches(
2331 options::OPT_cuda_device_only);
2332
2333 // Collect all cuda_gpu_arch parameters, removing duplicates.
2334 std::set<CudaArch> GpuArchs;
2335 bool Error = false;
2336 for (Arg *A : Args) {
2337 if (!(A->getOption().matches(options::OPT_cuda_gpu_arch_EQ) ||
2338 A->getOption().matches(options::OPT_no_cuda_gpu_arch_EQ)))
2339 continue;
2340 A->claim();
2341
2342 const StringRef ArchStr = A->getValue();
2343 if (A->getOption().matches(options::OPT_no_cuda_gpu_arch_EQ) &&
2344 ArchStr == "all") {
2345 GpuArchs.clear();
2346 continue;
2347 }
2348 CudaArch Arch = StringToCudaArch(ArchStr);
2349 if (Arch == CudaArch::UNKNOWN) {
2350 C.getDriver().Diag(clang::diag::err_drv_cuda_bad_gpu_arch) << ArchStr;
2351 Error = true;
2352 } else if (A->getOption().matches(options::OPT_cuda_gpu_arch_EQ))
2353 GpuArchs.insert(Arch);
2354 else if (A->getOption().matches(options::OPT_no_cuda_gpu_arch_EQ))
2355 GpuArchs.erase(Arch);
2356 else
2357 llvm_unreachable("Unexpected option.");
2358 }
2359
2360 // Collect list of GPUs remaining in the set.
2361 for (CudaArch Arch : GpuArchs)
2362 GpuArchList.push_back(Arch);
2363
2364 // Default to sm_20 which is the lowest common denominator for
2365 // supported GPUs. sm_20 code should work correctly, if
2366 // suboptimally, on all newer GPUs.
2367 if (GpuArchList.empty())
2368 GpuArchList.push_back(CudaArch::SM_20);
2369
2370 return Error;
2371 }
2372 };
2373
2374 /// \brief CUDA action builder. It injects device code in the host backend
2375 /// action.
2376 class CudaActionBuilder final : public CudaActionBuilderBase {
Samuel Antao64e965e2016-09-30 15:34:19 +00002377 public:
2378 CudaActionBuilder(Compilation &C, DerivedArgList &Args,
2379 const Driver::InputList &Inputs)
Yaxun Liu3af038b2018-05-30 00:49:10 +00002380 : CudaActionBuilderBase(C, Args, Inputs, Action::OFK_Cuda) {}
Samuel Antao64e965e2016-09-30 15:34:19 +00002381
2382 ActionBuilderReturnCode
Samuel Antao28c4f182016-10-27 17:08:03 +00002383 getDeviceDependences(OffloadAction::DeviceDependences &DA,
2384 phases::ID CurPhase, phases::ID FinalPhase,
2385 PhasesTy &Phases) override {
Samuel Antao64e965e2016-09-30 15:34:19 +00002386 if (!IsActive)
2387 return ABRT_Inactive;
2388
2389 // If we don't have more CUDA actions, we don't have any dependences to
2390 // create for the host.
2391 if (CudaDeviceActions.empty())
2392 return ABRT_Success;
2393
2394 assert(CudaDeviceActions.size() == GpuArchList.size() &&
2395 "Expecting one action per GPU architecture.");
2396 assert(!CompileHostOnly &&
2397 "Not expecting CUDA actions in host-only compilation.");
2398
2399 // If we are generating code for the device or we are in a backend phase,
2400 // we attempt to generate the fat binary. We compile each arch to ptx and
2401 // assemble to cubin, then feed the cubin *and* the ptx into a device
2402 // "link" action, which uses fatbinary to combine these cubins into one
2403 // fatbin. The fatbin is then an input to the host action if not in
2404 // device-only mode.
2405 if (CompileDeviceOnly || CurPhase == phases::Backend) {
2406 ActionList DeviceActions;
2407 for (unsigned I = 0, E = GpuArchList.size(); I != E; ++I) {
2408 // Produce the device action from the current phase up to the assemble
2409 // phase.
2410 for (auto Ph : Phases) {
2411 // Skip the phases that were already dealt with.
2412 if (Ph < CurPhase)
2413 continue;
2414 // We have to be consistent with the host final phase.
2415 if (Ph > FinalPhase)
2416 break;
2417
2418 CudaDeviceActions[I] = C.getDriver().ConstructPhaseAction(
Artem Belevichecb178b2018-03-21 22:22:59 +00002419 C, Args, Ph, CudaDeviceActions[I], Action::OFK_Cuda);
Samuel Antao64e965e2016-09-30 15:34:19 +00002420
2421 if (Ph == phases::Assemble)
2422 break;
2423 }
2424
2425 // If we didn't reach the assemble phase, we can't generate the fat
2426 // binary. We don't need to generate the fat binary if we are not in
2427 // device-only mode.
2428 if (!isa<AssembleJobAction>(CudaDeviceActions[I]) ||
2429 CompileDeviceOnly)
2430 continue;
2431
2432 Action *AssembleAction = CudaDeviceActions[I];
2433 assert(AssembleAction->getType() == types::TY_Object);
2434 assert(AssembleAction->getInputs().size() == 1);
2435
2436 Action *BackendAction = AssembleAction->getInputs()[0];
2437 assert(BackendAction->getType() == types::TY_PP_Asm);
2438
2439 for (auto &A : {AssembleAction, BackendAction}) {
2440 OffloadAction::DeviceDependences DDep;
2441 DDep.add(*A, *ToolChains.front(), CudaArchToString(GpuArchList[I]),
2442 Action::OFK_Cuda);
2443 DeviceActions.push_back(
2444 C.MakeAction<OffloadAction>(DDep, A->getType()));
2445 }
2446 }
2447
2448 // We generate the fat binary if we have device input actions.
2449 if (!DeviceActions.empty()) {
2450 CudaFatBinary =
2451 C.MakeAction<LinkJobAction>(DeviceActions, types::TY_CUDA_FATBIN);
2452
2453 if (!CompileDeviceOnly) {
2454 DA.add(*CudaFatBinary, *ToolChains.front(), /*BoundArch=*/nullptr,
2455 Action::OFK_Cuda);
2456 // Clear the fat binary, it is already a dependence to an host
2457 // action.
2458 CudaFatBinary = nullptr;
2459 }
2460
2461 // Remove the CUDA actions as they are already connected to an host
2462 // action or fat binary.
2463 CudaDeviceActions.clear();
2464 }
2465
2466 // We avoid creating host action in device-only mode.
2467 return CompileDeviceOnly ? ABRT_Ignore_Host : ABRT_Success;
Samuel Antao5b1a89a2016-10-27 00:53:34 +00002468 } else if (CurPhase > phases::Backend) {
2469 // If we are past the backend phase and still have a device action, we
2470 // don't have to do anything as this action is already a device
2471 // top-level action.
2472 return ABRT_Success;
Samuel Antao64e965e2016-09-30 15:34:19 +00002473 }
2474
2475 assert(CurPhase < phases::Backend && "Generating single CUDA "
2476 "instructions should only occur "
2477 "before the backend phase!");
2478
2479 // By default, we produce an action for each device arch.
2480 for (Action *&A : CudaDeviceActions)
2481 A = C.getDriver().ConstructPhaseAction(C, Args, CurPhase, A);
2482
2483 return ABRT_Success;
2484 }
Yaxun Liu3af038b2018-05-30 00:49:10 +00002485 };
2486 /// \brief HIP action builder. It injects device code in the host backend
2487 /// action.
2488 class HIPActionBuilder final : public CudaActionBuilderBase {
2489 /// The linker inputs obtained for each device arch.
2490 SmallVector<ActionList, 8> DeviceLinkerInputs;
Yaxun Liu97670892018-10-02 17:48:54 +00002491 bool Relocatable;
Samuel Antao64e965e2016-09-30 15:34:19 +00002492
Yaxun Liu3af038b2018-05-30 00:49:10 +00002493 public:
2494 HIPActionBuilder(Compilation &C, DerivedArgList &Args,
2495 const Driver::InputList &Inputs)
Yaxun Liu97670892018-10-02 17:48:54 +00002496 : CudaActionBuilderBase(C, Args, Inputs, Action::OFK_HIP),
2497 Relocatable(false) {}
Samuel Antao64e965e2016-09-30 15:34:19 +00002498
Yaxun Liu3af038b2018-05-30 00:49:10 +00002499 bool canUseBundlerUnbundler() const override { return true; }
Samuel Antao64e965e2016-09-30 15:34:19 +00002500
Yaxun Liu3af038b2018-05-30 00:49:10 +00002501 ActionBuilderReturnCode
2502 getDeviceDependences(OffloadAction::DeviceDependences &DA,
2503 phases::ID CurPhase, phases::ID FinalPhase,
2504 PhasesTy &Phases) override {
2505 // amdgcn does not support linking of object files, therefore we skip
Yaxun Liu97670892018-10-02 17:48:54 +00002506 // backend and assemble phases to output LLVM IR. Except for generating
2507 // non-relocatable device coee, where we generate fat binary for device
2508 // code and pass to host in Backend phase.
2509 if (CudaDeviceActions.empty() ||
2510 (CurPhase == phases::Backend && Relocatable) ||
Yaxun Liu3af038b2018-05-30 00:49:10 +00002511 CurPhase == phases::Assemble)
2512 return ABRT_Success;
2513
Yaxun Liu97670892018-10-02 17:48:54 +00002514 assert(((CurPhase == phases::Link && Relocatable) ||
Yaxun Liu3af038b2018-05-30 00:49:10 +00002515 CudaDeviceActions.size() == GpuArchList.size()) &&
2516 "Expecting one action per GPU architecture.");
2517 assert(!CompileHostOnly &&
2518 "Not expecting CUDA actions in host-only compilation.");
2519
Yaxun Liu97670892018-10-02 17:48:54 +00002520 if (!Relocatable && CurPhase == phases::Backend) {
2521 // If we are in backend phase, we attempt to generate the fat binary.
2522 // We compile each arch to IR and use a link action to generate code
2523 // object containing ISA. Then we use a special "link" action to create
2524 // a fat binary containing all the code objects for different GPU's.
2525 // The fat binary is then an input to the host action.
2526 for (unsigned I = 0, E = GpuArchList.size(); I != E; ++I) {
2527 // Create a link action to link device IR with device library
2528 // and generate ISA.
2529 ActionList AL;
2530 AL.push_back(CudaDeviceActions[I]);
2531 CudaDeviceActions[I] =
2532 C.MakeAction<LinkJobAction>(AL, types::TY_Image);
2533
2534 // OffloadingActionBuilder propagates device arch until an offload
2535 // action. Since the next action for creating fatbin does
2536 // not have device arch, whereas the above link action and its input
2537 // have device arch, an offload action is needed to stop the null
2538 // device arch of the next action being propagated to the above link
2539 // action.
2540 OffloadAction::DeviceDependences DDep;
2541 DDep.add(*CudaDeviceActions[I], *ToolChains.front(),
2542 CudaArchToString(GpuArchList[I]), AssociatedOffloadKind);
2543 CudaDeviceActions[I] = C.MakeAction<OffloadAction>(
2544 DDep, CudaDeviceActions[I]->getType());
2545 }
2546 // Create HIP fat binary with a special "link" action.
2547 CudaFatBinary =
2548 C.MakeAction<LinkJobAction>(CudaDeviceActions,
2549 types::TY_HIP_FATBIN);
2550
2551 DA.add(*CudaFatBinary, *ToolChains.front(), /*BoundArch=*/nullptr,
2552 AssociatedOffloadKind);
2553 // Clear the fat binary, it is already a dependence to an host
2554 // action.
2555 CudaFatBinary = nullptr;
2556
2557 // Remove the CUDA actions as they are already connected to an host
2558 // action or fat binary.
2559 CudaDeviceActions.clear();
2560
2561 return ABRT_Success;
2562 } else if (CurPhase == phases::Link) {
2563 // Save CudaDeviceActions to DeviceLinkerInputs for each GPU subarch.
2564 // This happens to each device action originated from each input file.
2565 // Later on, device actions in DeviceLinkerInputs are used to create
2566 // device link actions in appendLinkDependences and the created device
2567 // link actions are passed to the offload action as device dependence.
Yaxun Liu3af038b2018-05-30 00:49:10 +00002568 DeviceLinkerInputs.resize(CudaDeviceActions.size());
2569 auto LI = DeviceLinkerInputs.begin();
2570 for (auto *A : CudaDeviceActions) {
2571 LI->push_back(A);
2572 ++LI;
Samuel Antao64e965e2016-09-30 15:34:19 +00002573 }
2574
Yaxun Liu3af038b2018-05-30 00:49:10 +00002575 // We will pass the device action as a host dependence, so we don't
2576 // need to do anything else with them.
2577 CudaDeviceActions.clear();
Samuel Antao64e965e2016-09-30 15:34:19 +00002578 return ABRT_Success;
2579 }
2580
Yaxun Liu3af038b2018-05-30 00:49:10 +00002581 // By default, we produce an action for each device arch.
2582 for (Action *&A : CudaDeviceActions)
2583 A = C.getDriver().ConstructPhaseAction(C, Args, CurPhase, A,
2584 AssociatedOffloadKind);
2585
2586 return ABRT_Success;
Samuel Antao64e965e2016-09-30 15:34:19 +00002587 }
2588
Yaxun Liu3af038b2018-05-30 00:49:10 +00002589 void appendLinkDependences(OffloadAction::DeviceDependences &DA) override {
2590 // Append a new link action for each device.
2591 unsigned I = 0;
2592 for (auto &LI : DeviceLinkerInputs) {
2593 auto *DeviceLinkAction =
2594 C.MakeAction<LinkJobAction>(LI, types::TY_Image);
2595 DA.add(*DeviceLinkAction, *ToolChains[0],
2596 CudaArchToString(GpuArchList[I]), AssociatedOffloadKind);
2597 ++I;
Samuel Antao64e965e2016-09-30 15:34:19 +00002598 }
Samuel Antao64e965e2016-09-30 15:34:19 +00002599 }
Yaxun Liu97670892018-10-02 17:48:54 +00002600
2601 bool initialize() override {
2602 Relocatable = Args.hasFlag(options::OPT_fgpu_rdc,
2603 options::OPT_fno_gpu_rdc, /*Default=*/false);
2604
2605 return CudaActionBuilderBase::initialize();
2606 }
Samuel Antao64e965e2016-09-30 15:34:19 +00002607 };
2608
Samuel Antao28c4f182016-10-27 17:08:03 +00002609 /// OpenMP action builder. The host bitcode is passed to the device frontend
2610 /// and all the device linked images are passed to the host link phase.
2611 class OpenMPActionBuilder final : public DeviceActionBuilder {
2612 /// The OpenMP actions for the current input.
2613 ActionList OpenMPDeviceActions;
2614
2615 /// The linker inputs obtained for each toolchain.
2616 SmallVector<ActionList, 8> DeviceLinkerInputs;
2617
2618 public:
2619 OpenMPActionBuilder(Compilation &C, DerivedArgList &Args,
2620 const Driver::InputList &Inputs)
2621 : DeviceActionBuilder(C, Args, Inputs, Action::OFK_OpenMP) {}
2622
2623 ActionBuilderReturnCode
2624 getDeviceDependences(OffloadAction::DeviceDependences &DA,
2625 phases::ID CurPhase, phases::ID FinalPhase,
2626 PhasesTy &Phases) override {
Alexey Bataeva5178f52018-09-28 16:17:59 +00002627 if (OpenMPDeviceActions.empty())
2628 return ABRT_Inactive;
Samuel Antao28c4f182016-10-27 17:08:03 +00002629
2630 // We should always have an action for each input.
2631 assert(OpenMPDeviceActions.size() == ToolChains.size() &&
2632 "Number of OpenMP actions and toolchains do not match.");
2633
2634 // The host only depends on device action in the linking phase, when all
2635 // the device images have to be embedded in the host image.
2636 if (CurPhase == phases::Link) {
2637 assert(ToolChains.size() == DeviceLinkerInputs.size() &&
2638 "Toolchains and linker inputs sizes do not match.");
2639 auto LI = DeviceLinkerInputs.begin();
2640 for (auto *A : OpenMPDeviceActions) {
2641 LI->push_back(A);
2642 ++LI;
2643 }
2644
2645 // We passed the device action as a host dependence, so we don't need to
2646 // do anything else with them.
2647 OpenMPDeviceActions.clear();
2648 return ABRT_Success;
2649 }
2650
2651 // By default, we produce an action for each device arch.
2652 for (Action *&A : OpenMPDeviceActions)
2653 A = C.getDriver().ConstructPhaseAction(C, Args, CurPhase, A);
2654
2655 return ABRT_Success;
2656 }
2657
2658 ActionBuilderReturnCode addDeviceDepences(Action *HostAction) override {
2659
2660 // If this is an input action replicate it for each OpenMP toolchain.
2661 if (auto *IA = dyn_cast<InputAction>(HostAction)) {
2662 OpenMPDeviceActions.clear();
2663 for (unsigned I = 0; I < ToolChains.size(); ++I)
2664 OpenMPDeviceActions.push_back(
2665 C.MakeAction<InputAction>(IA->getInputArg(), IA->getType()));
2666 return ABRT_Success;
2667 }
2668
Samuel Antaofab4f372016-10-27 18:00:51 +00002669 // If this is an unbundling action use it as is for each OpenMP toolchain.
2670 if (auto *UA = dyn_cast<OffloadUnbundlingJobAction>(HostAction)) {
2671 OpenMPDeviceActions.clear();
Alexey Bataeva5178f52018-09-28 16:17:59 +00002672 auto *IA = cast<InputAction>(UA->getInputs().back());
2673 std::string FileName = IA->getInputArg().getAsString(Args);
2674 // Check if the type of the file is the same as the action. Do not
2675 // unbundle it if it is not. Do not unbundle .so files, for example,
2676 // which are not object files.
2677 if (IA->getType() == types::TY_Object &&
2678 (!llvm::sys::path::has_extension(FileName) ||
2679 types::lookupTypeForExtension(
2680 llvm::sys::path::extension(FileName).drop_front()) !=
2681 types::TY_Object))
2682 return ABRT_Inactive;
Samuel Antaofab4f372016-10-27 18:00:51 +00002683 for (unsigned I = 0; I < ToolChains.size(); ++I) {
2684 OpenMPDeviceActions.push_back(UA);
2685 UA->registerDependentActionInfo(
2686 ToolChains[I], /*BoundArch=*/StringRef(), Action::OFK_OpenMP);
2687 }
2688 return ABRT_Success;
2689 }
2690
Samuel Antao28c4f182016-10-27 17:08:03 +00002691 // When generating code for OpenMP we use the host compile phase result as
2692 // a dependence to the device compile phase so that it can learn what
2693 // declarations should be emitted. However, this is not the only use for
2694 // the host action, so we prevent it from being collapsed.
2695 if (isa<CompileJobAction>(HostAction)) {
2696 HostAction->setCannotBeCollapsedWithNextDependentAction();
2697 assert(ToolChains.size() == OpenMPDeviceActions.size() &&
2698 "Toolchains and device action sizes do not match.");
2699 OffloadAction::HostDependence HDep(
2700 *HostAction, *C.getSingleOffloadToolChain<Action::OFK_Host>(),
2701 /*BoundArch=*/nullptr, Action::OFK_OpenMP);
2702 auto TC = ToolChains.begin();
2703 for (Action *&A : OpenMPDeviceActions) {
2704 assert(isa<CompileJobAction>(A));
2705 OffloadAction::DeviceDependences DDep;
2706 DDep.add(*A, **TC, /*BoundArch=*/nullptr, Action::OFK_OpenMP);
2707 A = C.MakeAction<OffloadAction>(HDep, DDep);
2708 ++TC;
2709 }
2710 }
2711 return ABRT_Success;
2712 }
2713
Samuel Antao69d6f312016-10-27 17:50:43 +00002714 void appendTopLevelActions(ActionList &AL) override {
2715 if (OpenMPDeviceActions.empty())
2716 return;
2717
2718 // We should always have an action for each input.
2719 assert(OpenMPDeviceActions.size() == ToolChains.size() &&
2720 "Number of OpenMP actions and toolchains do not match.");
2721
2722 // Append all device actions followed by the proper offload action.
2723 auto TI = ToolChains.begin();
2724 for (auto *A : OpenMPDeviceActions) {
2725 OffloadAction::DeviceDependences Dep;
2726 Dep.add(*A, **TI, /*BoundArch=*/nullptr, Action::OFK_OpenMP);
2727 AL.push_back(C.MakeAction<OffloadAction>(Dep, A->getType()));
2728 ++TI;
2729 }
2730 // We no longer need the action stored in this builder.
2731 OpenMPDeviceActions.clear();
2732 }
2733
Samuel Antao28c4f182016-10-27 17:08:03 +00002734 void appendLinkDependences(OffloadAction::DeviceDependences &DA) override {
2735 assert(ToolChains.size() == DeviceLinkerInputs.size() &&
2736 "Toolchains and linker inputs sizes do not match.");
2737
2738 // Append a new link action for each device.
2739 auto TC = ToolChains.begin();
2740 for (auto &LI : DeviceLinkerInputs) {
2741 auto *DeviceLinkAction =
2742 C.MakeAction<LinkJobAction>(LI, types::TY_Image);
2743 DA.add(*DeviceLinkAction, **TC, /*BoundArch=*/nullptr,
2744 Action::OFK_OpenMP);
2745 ++TC;
2746 }
2747 }
2748
2749 bool initialize() override {
2750 // Get the OpenMP toolchains. If we don't get any, the action builder will
2751 // know there is nothing to do related to OpenMP offloading.
2752 auto OpenMPTCRange = C.getOffloadToolChains<Action::OFK_OpenMP>();
2753 for (auto TI = OpenMPTCRange.first, TE = OpenMPTCRange.second; TI != TE;
2754 ++TI)
2755 ToolChains.push_back(TI->second);
2756
2757 DeviceLinkerInputs.resize(ToolChains.size());
2758 return false;
2759 }
Samuel Antao69d6f312016-10-27 17:50:43 +00002760
2761 bool canUseBundlerUnbundler() const override {
2762 // OpenMP should use bundled files whenever possible.
2763 return true;
2764 }
Samuel Antao28c4f182016-10-27 17:08:03 +00002765 };
2766
2767 ///
2768 /// TODO: Add the implementation for other specialized builders here.
2769 ///
Samuel Antao64e965e2016-09-30 15:34:19 +00002770
2771 /// Specialized builders being used by this offloading action builder.
2772 SmallVector<DeviceActionBuilder *, 4> SpecializedBuilders;
2773
Samuel Antao69d6f312016-10-27 17:50:43 +00002774 /// Flag set to true if all valid builders allow file bundling/unbundling.
2775 bool CanUseBundler;
2776
Samuel Antao64e965e2016-09-30 15:34:19 +00002777public:
2778 OffloadingActionBuilder(Compilation &C, DerivedArgList &Args,
2779 const Driver::InputList &Inputs)
Samuel Antao10e905c2016-10-27 01:08:58 +00002780 : C(C) {
Samuel Antao64e965e2016-09-30 15:34:19 +00002781 // Create a specialized builder for each device toolchain.
2782
2783 IsValid = true;
2784
2785 // Create a specialized builder for CUDA.
2786 SpecializedBuilders.push_back(new CudaActionBuilder(C, Args, Inputs));
2787
Yaxun Liu3af038b2018-05-30 00:49:10 +00002788 // Create a specialized builder for HIP.
2789 SpecializedBuilders.push_back(new HIPActionBuilder(C, Args, Inputs));
2790
Samuel Antao28c4f182016-10-27 17:08:03 +00002791 // Create a specialized builder for OpenMP.
2792 SpecializedBuilders.push_back(new OpenMPActionBuilder(C, Args, Inputs));
2793
Samuel Antao64e965e2016-09-30 15:34:19 +00002794 //
2795 // TODO: Build other specialized builders here.
2796 //
2797
Samuel Antao69d6f312016-10-27 17:50:43 +00002798 // Initialize all the builders, keeping track of errors. If all valid
2799 // builders agree that we can use bundling, set the flag to true.
2800 unsigned ValidBuilders = 0u;
2801 unsigned ValidBuildersSupportingBundling = 0u;
2802 for (auto *SB : SpecializedBuilders) {
Samuel Antao64e965e2016-09-30 15:34:19 +00002803 IsValid = IsValid && !SB->initialize();
Samuel Antao69d6f312016-10-27 17:50:43 +00002804
2805 // Update the counters if the builder is valid.
2806 if (SB->isValid()) {
2807 ++ValidBuilders;
2808 if (SB->canUseBundlerUnbundler())
2809 ++ValidBuildersSupportingBundling;
2810 }
2811 }
2812 CanUseBundler =
2813 ValidBuilders && ValidBuilders == ValidBuildersSupportingBundling;
Artem Belevichf981e30b2016-08-02 22:37:47 +00002814 }
Justin Lebardc3c5042016-04-19 02:27:07 +00002815
Samuel Antao64e965e2016-09-30 15:34:19 +00002816 ~OffloadingActionBuilder() {
2817 for (auto *SB : SpecializedBuilders)
2818 delete SB;
Samuel Antaod06239d2016-07-15 23:13:27 +00002819 }
Artem Belevich0ff05cd2015-07-13 23:27:56 +00002820
Samuel Antao64e965e2016-09-30 15:34:19 +00002821 /// Generate an action that adds device dependences (if any) to a host action.
2822 /// If no device dependence actions exist, just return the host action \a
2823 /// HostAction. If an error is found or if no builder requires the host action
2824 /// to be generated, return nullptr.
2825 Action *
2826 addDeviceDependencesToHostAction(Action *HostAction, const Arg *InputArg,
2827 phases::ID CurPhase, phases::ID FinalPhase,
2828 DeviceActionBuilder::PhasesTy &Phases) {
2829 if (!IsValid)
2830 return nullptr;
Justin Lebar7bf77982016-01-11 23:27:13 +00002831
Samuel Antao64e965e2016-09-30 15:34:19 +00002832 if (SpecializedBuilders.empty())
2833 return HostAction;
2834
2835 assert(HostAction && "Invalid host action!");
2836
2837 OffloadAction::DeviceDependences DDeps;
2838 // Check if all the programming models agree we should not emit the host
2839 // action. Also, keep track of the offloading kinds employed.
2840 auto &OffloadKind = InputArgToOffloadKindMap[InputArg];
2841 unsigned InactiveBuilders = 0u;
2842 unsigned IgnoringBuilders = 0u;
2843 for (auto *SB : SpecializedBuilders) {
2844 if (!SB->isValid()) {
2845 ++InactiveBuilders;
2846 continue;
2847 }
2848
Samuel Antao28c4f182016-10-27 17:08:03 +00002849 auto RetCode =
2850 SB->getDeviceDependences(DDeps, CurPhase, FinalPhase, Phases);
Samuel Antao64e965e2016-09-30 15:34:19 +00002851
2852 // If the builder explicitly says the host action should be ignored,
2853 // we need to increment the variable that tracks the builders that request
2854 // the host object to be ignored.
2855 if (RetCode == DeviceActionBuilder::ABRT_Ignore_Host)
2856 ++IgnoringBuilders;
2857
2858 // Unless the builder was inactive for this action, we have to record the
2859 // offload kind because the host will have to use it.
2860 if (RetCode != DeviceActionBuilder::ABRT_Inactive)
2861 OffloadKind |= SB->getAssociatedOffloadKind();
2862 }
2863
2864 // If all builders agree that the host object should be ignored, just return
2865 // nullptr.
2866 if (IgnoringBuilders &&
2867 SpecializedBuilders.size() == (InactiveBuilders + IgnoringBuilders))
2868 return nullptr;
2869
2870 if (DDeps.getActions().empty())
2871 return HostAction;
2872
2873 // We have dependences we need to bundle together. We use an offload action
2874 // for that.
2875 OffloadAction::HostDependence HDep(
2876 *HostAction, *C.getSingleOffloadToolChain<Action::OFK_Host>(),
2877 /*BoundArch=*/nullptr, DDeps);
2878 return C.MakeAction<OffloadAction>(HDep, DDeps);
Artem Belevich0ff05cd2015-07-13 23:27:56 +00002879 }
2880
Samuel Antao64e965e2016-09-30 15:34:19 +00002881 /// Generate an action that adds a host dependence to a device action. The
2882 /// results will be kept in this action builder. Return true if an error was
2883 /// found.
Samuel Antaofab4f372016-10-27 18:00:51 +00002884 bool addHostDependenceToDeviceActions(Action *&HostAction,
Samuel Antao64e965e2016-09-30 15:34:19 +00002885 const Arg *InputArg) {
2886 if (!IsValid)
2887 return true;
Artem Belevich0ff05cd2015-07-13 23:27:56 +00002888
Samuel Antaofab4f372016-10-27 18:00:51 +00002889 // If we are supporting bundling/unbundling and the current action is an
2890 // input action of non-source file, we replace the host action by the
2891 // unbundling action. The bundler tool has the logic to detect if an input
2892 // is a bundle or not and if the input is not a bundle it assumes it is a
2893 // host file. Therefore it is safe to create an unbundling action even if
2894 // the input is not a bundle.
2895 if (CanUseBundler && isa<InputAction>(HostAction) &&
2896 InputArg->getOption().getKind() == llvm::opt::Option::InputClass &&
2897 !types::isSrcFile(HostAction->getType())) {
2898 auto UnbundlingHostAction =
2899 C.MakeAction<OffloadUnbundlingJobAction>(HostAction);
2900 UnbundlingHostAction->registerDependentActionInfo(
2901 C.getSingleOffloadToolChain<Action::OFK_Host>(),
Yaxun Liuf37b50a2018-07-24 01:03:44 +00002902 /*BoundArch=*/StringRef(), Action::OFK_Host);
Samuel Antaofab4f372016-10-27 18:00:51 +00002903 HostAction = UnbundlingHostAction;
2904 }
2905
Samuel Antao64e965e2016-09-30 15:34:19 +00002906 assert(HostAction && "Invalid host action!");
Artem Belevich0ff05cd2015-07-13 23:27:56 +00002907
Samuel Antao64e965e2016-09-30 15:34:19 +00002908 // Register the offload kinds that are used.
2909 auto &OffloadKind = InputArgToOffloadKindMap[InputArg];
2910 for (auto *SB : SpecializedBuilders) {
2911 if (!SB->isValid())
2912 continue;
Artem Belevich0ff05cd2015-07-13 23:27:56 +00002913
Samuel Antao64e965e2016-09-30 15:34:19 +00002914 auto RetCode = SB->addDeviceDepences(HostAction);
Artem Belevich0ff05cd2015-07-13 23:27:56 +00002915
Samuel Antao64e965e2016-09-30 15:34:19 +00002916 // Host dependences for device actions are not compatible with that same
2917 // action being ignored.
2918 assert(RetCode != DeviceActionBuilder::ABRT_Ignore_Host &&
2919 "Host dependence not expected to be ignored.!");
Samuel Antaod06239d2016-07-15 23:13:27 +00002920
Samuel Antao64e965e2016-09-30 15:34:19 +00002921 // Unless the builder was inactive for this action, we have to record the
2922 // offload kind because the host will have to use it.
2923 if (RetCode != DeviceActionBuilder::ABRT_Inactive)
2924 OffloadKind |= SB->getAssociatedOffloadKind();
2925 }
Artem Belevich0ff05cd2015-07-13 23:27:56 +00002926
Alexey Bataeva5178f52018-09-28 16:17:59 +00002927 // Do not use unbundler if the Host does not depend on device action.
2928 if (OffloadKind == Action::OFK_None && CanUseBundler)
2929 if (auto *UA = dyn_cast<OffloadUnbundlingJobAction>(HostAction))
2930 HostAction = UA->getInputs().back();
2931
Samuel Antao64e965e2016-09-30 15:34:19 +00002932 return false;
2933 }
2934
Samuel Antao69d6f312016-10-27 17:50:43 +00002935 /// Add the offloading top level actions to the provided action list. This
2936 /// function can replace the host action by a bundling action if the
2937 /// programming models allow it.
Samuel Antao64e965e2016-09-30 15:34:19 +00002938 bool appendTopLevelActions(ActionList &AL, Action *HostAction,
2939 const Arg *InputArg) {
Samuel Antao69d6f312016-10-27 17:50:43 +00002940 // Get the device actions to be appended.
2941 ActionList OffloadAL;
Samuel Antao64e965e2016-09-30 15:34:19 +00002942 for (auto *SB : SpecializedBuilders) {
2943 if (!SB->isValid())
2944 continue;
Samuel Antao69d6f312016-10-27 17:50:43 +00002945 SB->appendTopLevelActions(OffloadAL);
Samuel Antao64e965e2016-09-30 15:34:19 +00002946 }
2947
Samuel Antao69d6f312016-10-27 17:50:43 +00002948 // If we can use the bundler, replace the host action by the bundling one in
2949 // the resulting list. Otherwise, just append the device actions.
2950 if (CanUseBundler && !OffloadAL.empty()) {
2951 // Add the host action to the list in order to create the bundling action.
2952 OffloadAL.push_back(HostAction);
2953
2954 // We expect that the host action was just appended to the action list
2955 // before this method was called.
2956 assert(HostAction == AL.back() && "Host action not in the list??");
2957 HostAction = C.MakeAction<OffloadBundlingJobAction>(OffloadAL);
2958 AL.back() = HostAction;
2959 } else
2960 AL.append(OffloadAL.begin(), OffloadAL.end());
2961
Samuel Antao64e965e2016-09-30 15:34:19 +00002962 // Propagate to the current host action (if any) the offload information
2963 // associated with the current input.
2964 if (HostAction)
2965 HostAction->propagateHostOffloadInfo(InputArgToOffloadKindMap[InputArg],
2966 /*BoundArch=*/nullptr);
Samuel Antao64e965e2016-09-30 15:34:19 +00002967 return false;
Artem Belevich0ff05cd2015-07-13 23:27:56 +00002968 }
Artem Belevich5bde4e02015-07-20 20:02:54 +00002969
Samuel Antao64e965e2016-09-30 15:34:19 +00002970 /// Processes the host linker action. This currently consists of replacing it
2971 /// with an offload action if there are device link objects and propagate to
2972 /// the host action all the offload kinds used in the current compilation. The
2973 /// resulting action is returned.
2974 Action *processHostLinkAction(Action *HostAction) {
2975 // Add all the dependences from the device linking actions.
2976 OffloadAction::DeviceDependences DDeps;
2977 for (auto *SB : SpecializedBuilders) {
2978 if (!SB->isValid())
2979 continue;
Justin Lebar21e5d4f2016-01-14 21:41:27 +00002980
Samuel Antao64e965e2016-09-30 15:34:19 +00002981 SB->appendLinkDependences(DDeps);
Justin Lebar21e5d4f2016-01-14 21:41:27 +00002982 }
Samuel Antaod06239d2016-07-15 23:13:27 +00002983
Samuel Antao64e965e2016-09-30 15:34:19 +00002984 // Calculate all the offload kinds used in the current compilation.
2985 unsigned ActiveOffloadKinds = 0u;
2986 for (auto &I : InputArgToOffloadKindMap)
2987 ActiveOffloadKinds |= I.second;
2988
2989 // If we don't have device dependencies, we don't have to create an offload
2990 // action.
2991 if (DDeps.getActions().empty()) {
2992 // Propagate all the active kinds to host action. Given that it is a link
2993 // action it is assumed to depend on all actions generated so far.
2994 HostAction->propagateHostOffloadInfo(ActiveOffloadKinds,
2995 /*BoundArch=*/nullptr);
2996 return HostAction;
2997 }
2998
2999 // Create the offload action with all dependences. When an offload action
3000 // is created the kinds are propagated to the host action, so we don't have
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00003001 // to do that explicitly here.
Samuel Antao64e965e2016-09-30 15:34:19 +00003002 OffloadAction::HostDependence HDep(
3003 *HostAction, *C.getSingleOffloadToolChain<Action::OFK_Host>(),
3004 /*BoundArch*/ nullptr, ActiveOffloadKinds);
3005 return C.MakeAction<OffloadAction>(HDep, DDeps);
3006 }
3007};
3008} // anonymous namespace.
Artem Belevich0ff05cd2015-07-13 23:27:56 +00003009
Justin Lebar0f3474c2016-02-11 02:00:50 +00003010void Driver::BuildActions(Compilation &C, DerivedArgList &Args,
3011 const InputList &Inputs, ActionList &Actions) const {
Chad Rosierecdede82011-08-12 22:08:57 +00003012 llvm::PrettyStackTraceString CrashInfo("Building compilation actions");
Joerg Sonnenbergerb86f5f42011-03-06 23:31:01 +00003013
Daniel Dunbar34c41872009-03-13 00:17:48 +00003014 if (!SuppressMissingInputWarning && Inputs.empty()) {
Daniel Dunbarbfeec742009-03-12 23:55:14 +00003015 Diag(clang::diag::err_drv_no_input_files);
3016 return;
3017 }
3018
Chad Rosier7742b5d2011-07-27 23:36:45 +00003019 Arg *FinalPhaseArg;
3020 phases::ID FinalPhase = getFinalPhase(Args, &FinalPhaseArg);
Daniel Dunbarbfeec742009-03-12 23:55:14 +00003021
Bob Haarmanaaf51912017-02-27 19:40:19 +00003022 if (FinalPhase == phases::Link) {
3023 if (Args.hasArg(options::OPT_emit_llvm))
3024 Diag(clang::diag::err_drv_emit_llvm_link);
3025 if (IsCLMode() && LTOMode != LTOK_None &&
3026 !Args.getLastArgValue(options::OPT_fuse_ld_EQ).equals_lower("lld"))
3027 Diag(clang::diag::err_drv_lto_without_lld);
Rafael Espindolae8025642013-08-25 14:27:09 +00003028 }
3029
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00003030 // Reject -Z* at the top level, these options should never have been exposed
3031 // by gcc.
Daniel Dunbardd765242009-03-26 16:12:09 +00003032 if (Arg *A = Args.getLastArg(options::OPT_Z_Joined))
Daniel Dunbar0e759942009-03-20 06:14:23 +00003033 Diag(clang::diag::err_drv_use_of_Z_option) << A->getAsString(Args);
Daniel Dunbarbfeec742009-03-12 23:55:14 +00003034
Hans Wennborg13b7fe72013-08-12 23:26:25 +00003035 // Diagnose misuse of /Fo.
3036 if (Arg *A = Args.getLastArg(options::OPT__SLASH_Fo)) {
Hans Wennborg13b7fe72013-08-12 23:26:25 +00003037 StringRef V = A->getValue();
Hans Wennborg61647532014-11-17 19:16:36 +00003038 if (Inputs.size() > 1 && !V.empty() &&
3039 !llvm::sys::path::is_separator(V.back())) {
Hans Wennborg13b7fe72013-08-12 23:26:25 +00003040 // Check whether /Fo tries to name an output file for multiple inputs.
Hans Wennborg9c1659b2013-10-18 22:49:04 +00003041 Diag(clang::diag::err_drv_out_file_argument_with_multiple_sources)
Douglas Katzmana67e50c2015-06-26 15:47:46 +00003042 << A->getSpelling() << V;
Hans Wennborg13b7fe72013-08-12 23:26:25 +00003043 Args.eraseArg(options::OPT__SLASH_Fo);
3044 }
3045 }
3046
Hans Wennborg9c1659b2013-10-18 22:49:04 +00003047 // Diagnose misuse of /Fa.
3048 if (Arg *A = Args.getLastArg(options::OPT__SLASH_Fa)) {
3049 StringRef V = A->getValue();
Hans Wennborg61647532014-11-17 19:16:36 +00003050 if (Inputs.size() > 1 && !V.empty() &&
3051 !llvm::sys::path::is_separator(V.back())) {
Hans Wennborg9c1659b2013-10-18 22:49:04 +00003052 // Check whether /Fa tries to name an asm file for multiple inputs.
3053 Diag(clang::diag::err_drv_out_file_argument_with_multiple_sources)
Douglas Katzmana67e50c2015-06-26 15:47:46 +00003054 << A->getSpelling() << V;
Hans Wennborg9c1659b2013-10-18 22:49:04 +00003055 Args.eraseArg(options::OPT__SLASH_Fa);
3056 }
3057 }
3058
Ehsan Akhgari81f36b72014-09-11 18:16:21 +00003059 // Diagnose misuse of /o.
3060 if (Arg *A = Args.getLastArg(options::OPT__SLASH_o)) {
3061 if (A->getValue()[0] == '\0') {
3062 // It has to have a value.
3063 Diag(clang::diag::err_drv_missing_argument) << A->getSpelling() << 1;
3064 Args.eraseArg(options::OPT__SLASH_o);
3065 }
3066 }
3067
Mike Rice58df1af2018-09-11 17:10:44 +00003068 // Ignore /Yc/Yu if both /Yc and /Yu passed but with different filenames.
Nico Weber2ca4be92016-03-01 23:16:44 +00003069 Arg *YcArg = Args.getLastArg(options::OPT__SLASH_Yc);
3070 Arg *YuArg = Args.getLastArg(options::OPT__SLASH_Yu);
Nico Weber2ca4be92016-03-01 23:16:44 +00003071 if (YcArg && YuArg && strcmp(YcArg->getValue(), YuArg->getValue()) != 0) {
3072 Diag(clang::diag::warn_drv_ycyu_different_arg_clang_cl);
3073 Args.eraseArg(options::OPT__SLASH_Yc);
3074 Args.eraseArg(options::OPT__SLASH_Yu);
3075 YcArg = YuArg = nullptr;
3076 }
Nico Weber2ca4be92016-03-01 23:16:44 +00003077 if (YcArg && Inputs.size() > 1) {
3078 Diag(clang::diag::warn_drv_yc_multiple_inputs_clang_cl);
3079 Args.eraseArg(options::OPT__SLASH_Yc);
3080 YcArg = nullptr;
3081 }
Erich Keaneeaca3882018-08-17 13:43:39 +00003082 if (FinalPhase == phases::Preprocess || Args.hasArg(options::OPT__SLASH_Y_)) {
3083 // If only preprocessing or /Y- is used, all pch handling is disabled.
3084 // Rather than check for it everywhere, just remove clang-cl pch-related
3085 // flags here.
Nico Weber2ca4be92016-03-01 23:16:44 +00003086 Args.eraseArg(options::OPT__SLASH_Fp);
3087 Args.eraseArg(options::OPT__SLASH_Yc);
3088 Args.eraseArg(options::OPT__SLASH_Yu);
3089 YcArg = YuArg = nullptr;
3090 }
Nico Weber2ca4be92016-03-01 23:16:44 +00003091
Samuel Antao64e965e2016-09-30 15:34:19 +00003092 // Builder to be used to build offloading actions.
3093 OffloadingActionBuilder OffloadBuilder(C, Args, Inputs);
Samuel Antaod06239d2016-07-15 23:13:27 +00003094
Daniel Dunbar65229332009-03-13 11:38:42 +00003095 // Construct the actions to perform.
Richard Smithcd35eff2018-09-15 01:21:16 +00003096 HeaderModulePrecompileJobAction *HeaderModuleAction = nullptr;
Daniel Dunbar65229332009-03-13 11:38:42 +00003097 ActionList LinkerInputs;
Alp Toker965f8822013-11-27 05:22:15 +00003098
Matthew Curtis7ab8b2b2013-03-07 12:32:26 +00003099 llvm::SmallVector<phases::ID, phases::MaxNumberOfPhases> PL;
Artem Belevich5bde4e02015-07-20 20:02:54 +00003100 for (auto &I : Inputs) {
3101 types::ID InputType = I.first;
3102 const Arg *InputArg = I.second;
Daniel Dunbar65229332009-03-13 11:38:42 +00003103
Matthew Curtis7ab8b2b2013-03-07 12:32:26 +00003104 PL.clear();
3105 types::getCompilationPhases(InputType, PL);
Daniel Dunbar65229332009-03-13 11:38:42 +00003106
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00003107 // If the first step comes after the final phase we are doing as part of
3108 // this compilation, warn the user about it.
Matthew Curtis7ab8b2b2013-03-07 12:32:26 +00003109 phases::ID InitialPhase = PL[0];
Daniel Dunbar65229332009-03-13 11:38:42 +00003110 if (InitialPhase > FinalPhase) {
Martin Storsjo665c7a42018-05-04 06:05:58 +00003111 if (InputArg->isClaimed())
3112 continue;
3113
Daniel Dunbaradc5c7c2009-03-19 07:57:08 +00003114 // Claim here to avoid the more general unused warning.
3115 InputArg->claim();
Daniel Dunbar07806ca2009-09-17 04:13:26 +00003116
Daniel Dunbar2db3e732011-04-20 15:44:48 +00003117 // Suppress all unused style warnings with -Qunused-arguments
3118 if (Args.hasArg(options::OPT_Qunused_arguments))
3119 continue;
3120
Richard Smith403f76e2012-08-06 04:09:06 +00003121 // Special case when final phase determined by binary name, rather than
3122 // by a command-line argument with a corresponding Arg.
Hans Wennborg70850d82013-07-18 20:29:38 +00003123 if (CCCIsCPP())
Richard Smith403f76e2012-08-06 04:09:06 +00003124 Diag(clang::diag::warn_drv_input_file_unused_by_cpp)
Douglas Katzmana67e50c2015-06-26 15:47:46 +00003125 << InputArg->getAsString(Args) << getPhaseName(InitialPhase);
Daniel Dunbar07806ca2009-09-17 04:13:26 +00003126 // Special case '-E' warning on a previously preprocessed file to make
3127 // more sense.
Richard Smith403f76e2012-08-06 04:09:06 +00003128 else if (InitialPhase == phases::Compile &&
3129 FinalPhase == phases::Preprocess &&
3130 getPreprocessedType(InputType) == types::TY_INVALID)
Daniel Dunbar07806ca2009-09-17 04:13:26 +00003131 Diag(clang::diag::warn_drv_preprocessed_input_file_unused)
Douglas Katzmana67e50c2015-06-26 15:47:46 +00003132 << InputArg->getAsString(Args) << !!FinalPhaseArg
3133 << (FinalPhaseArg ? FinalPhaseArg->getOption().getName() : "");
Daniel Dunbar07806ca2009-09-17 04:13:26 +00003134 else
3135 Diag(clang::diag::warn_drv_input_file_unused)
Douglas Katzmana67e50c2015-06-26 15:47:46 +00003136 << InputArg->getAsString(Args) << getPhaseName(InitialPhase)
3137 << !!FinalPhaseArg
3138 << (FinalPhaseArg ? FinalPhaseArg->getOption().getName() : "");
Daniel Dunbar65229332009-03-13 11:38:42 +00003139 continue;
3140 }
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00003141
Nico Weberad2d8f32016-04-21 19:59:10 +00003142 if (YcArg) {
3143 // Add a separate precompile phase for the compile phase.
3144 if (FinalPhase >= phases::Compile) {
Richard Smith8cd452d2016-08-30 18:55:16 +00003145 const types::ID HeaderType = lookupHeaderTypeForSourceType(InputType);
Nico Weberad2d8f32016-04-21 19:59:10 +00003146 llvm::SmallVector<phases::ID, phases::MaxNumberOfPhases> PCHPL;
Richard Smith8cd452d2016-08-30 18:55:16 +00003147 types::getCompilationPhases(HeaderType, PCHPL);
Nico Weberad2d8f32016-04-21 19:59:10 +00003148 // Build the pipeline for the pch file.
Richard Smith8cd452d2016-08-30 18:55:16 +00003149 Action *ClangClPch =
Erich Keane76675de2018-07-05 17:22:13 +00003150 C.MakeAction<InputAction>(*InputArg, HeaderType);
Nico Weberad2d8f32016-04-21 19:59:10 +00003151 for (phases::ID Phase : PCHPL)
3152 ClangClPch = ConstructPhaseAction(C, Args, Phase, ClangClPch);
3153 assert(ClangClPch);
3154 Actions.push_back(ClangClPch);
3155 // The driver currently exits after the first failed command. This
3156 // relies on that behavior, to make sure if the pch generation fails,
3157 // the main compilation won't run.
Hans Wennborg08c5a7b2018-06-25 13:23:49 +00003158 // FIXME: If the main compilation fails, the PCH generation should
3159 // probably not be considered successful either.
Nico Weberad2d8f32016-04-21 19:59:10 +00003160 }
3161 }
3162
Daniel Dunbar65229332009-03-13 11:38:42 +00003163 // Build the pipeline for this file.
Justin Lebar41094612016-01-11 23:07:27 +00003164 Action *Current = C.MakeAction<InputAction>(*InputArg, InputType);
Samuel Antao64e965e2016-09-30 15:34:19 +00003165
3166 // Use the current host action in any of the offloading actions, if
3167 // required.
3168 if (OffloadBuilder.addHostDependenceToDeviceActions(Current, InputArg))
3169 break;
3170
Douglas Katzmana67e50c2015-06-26 15:47:46 +00003171 for (SmallVectorImpl<phases::ID>::iterator i = PL.begin(), e = PL.end();
3172 i != e; ++i) {
Matthew Curtis7ab8b2b2013-03-07 12:32:26 +00003173 phases::ID Phase = *i;
Daniel Dunbar65229332009-03-13 11:38:42 +00003174
3175 // We are done if this step is past what the user requested.
3176 if (Phase > FinalPhase)
3177 break;
3178
Samuel Antao64e965e2016-09-30 15:34:19 +00003179 // Add any offload action the host action depends on.
3180 Current = OffloadBuilder.addDeviceDependencesToHostAction(
3181 Current, InputArg, Phase, FinalPhase, PL);
3182 if (!Current)
3183 break;
3184
Daniel Dunbar65229332009-03-13 11:38:42 +00003185 // Queue linker inputs.
3186 if (Phase == phases::Link) {
Matthew Curtis7ab8b2b2013-03-07 12:32:26 +00003187 assert((i + 1) == e && "linking must be final compilation step.");
Justin Lebar41094612016-01-11 23:07:27 +00003188 LinkerInputs.push_back(Current);
3189 Current = nullptr;
Daniel Dunbar65229332009-03-13 11:38:42 +00003190 break;
3191 }
3192
Richard Smithcd35eff2018-09-15 01:21:16 +00003193 // Each precompiled header file after a module file action is a module
3194 // header of that same module file, rather than being compiled to a
3195 // separate PCH.
3196 if (Phase == phases::Precompile && HeaderModuleAction &&
3197 getPrecompiledType(InputType) == types::TY_PCH) {
3198 HeaderModuleAction->addModuleHeaderInput(Current);
3199 Current = nullptr;
3200 break;
3201 }
3202
3203 // FIXME: Should we include any prior module file outputs as inputs of
3204 // later actions in the same command line?
3205
Samuel Antao64e965e2016-09-30 15:34:19 +00003206 // Otherwise construct the appropriate action.
Richard Smithcd35eff2018-09-15 01:21:16 +00003207 Action *NewCurrent = ConstructPhaseAction(C, Args, Phase, Current);
Samuel Antao64e965e2016-09-30 15:34:19 +00003208
3209 // We didn't create a new action, so we will just move to the next phase.
3210 if (NewCurrent == Current)
Daniel Dunbar13864952009-03-24 20:17:30 +00003211 continue;
3212
Richard Smithcd35eff2018-09-15 01:21:16 +00003213 if (auto *HMA = dyn_cast<HeaderModulePrecompileJobAction>(NewCurrent))
3214 HeaderModuleAction = HMA;
3215
Samuel Antao64e965e2016-09-30 15:34:19 +00003216 Current = NewCurrent;
Artem Belevich0ff05cd2015-07-13 23:27:56 +00003217
Samuel Antao64e965e2016-09-30 15:34:19 +00003218 // Use the current host action in any of the offloading actions, if
3219 // required.
3220 if (OffloadBuilder.addHostDependenceToDeviceActions(Current, InputArg))
3221 break;
Artem Belevich0ff05cd2015-07-13 23:27:56 +00003222
Daniel Dunbar65229332009-03-13 11:38:42 +00003223 if (Current->getType() == types::TY_Nothing)
3224 break;
3225 }
3226
Samuel Antao64e965e2016-09-30 15:34:19 +00003227 // If we ended with something, add to the output list.
3228 if (Current)
Justin Lebar41094612016-01-11 23:07:27 +00003229 Actions.push_back(Current);
Samuel Antao64e965e2016-09-30 15:34:19 +00003230
3231 // Add any top level actions generated for offloading.
3232 OffloadBuilder.appendTopLevelActions(Actions, Current, InputArg);
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00003233 }
Daniel Dunbar65229332009-03-13 11:38:42 +00003234
Samuel Antao64e965e2016-09-30 15:34:19 +00003235 // Add a link action if necessary.
Samuel Antaod06239d2016-07-15 23:13:27 +00003236 if (!LinkerInputs.empty()) {
Samuel Antao64e965e2016-09-30 15:34:19 +00003237 Action *LA = C.MakeAction<LinkJobAction>(LinkerInputs, types::TY_Image);
3238 LA = OffloadBuilder.processHostLinkAction(LA);
3239 Actions.push_back(LA);
Samuel Antaod06239d2016-07-15 23:13:27 +00003240 }
Daniel Dunbarc7a67b72009-12-22 23:19:32 +00003241
3242 // If we are linking, claim any options which are obviously only used for
3243 // compilation.
Hans Wennborga8ef14f2013-09-17 00:03:41 +00003244 if (FinalPhase == phases::Link && PL.size() == 1) {
Daniel Dunbarc7a67b72009-12-22 23:19:32 +00003245 Args.ClaimAllArgs(options::OPT_CompileOnly_Group);
Hans Wennborga8ef14f2013-09-17 00:03:41 +00003246 Args.ClaimAllArgs(options::OPT_cl_compile_Group);
3247 }
3248
3249 // Claim ignored clang-cl options.
3250 Args.ClaimAllArgs(options::OPT_cl_ignored_Group);
Artem Belevichbaae0932015-07-28 21:01:30 +00003251
Justin Lebardc3c5042016-04-19 02:27:07 +00003252 // Claim --cuda-host-only and --cuda-compile-host-device, which may be passed
3253 // to non-CUDA compilations and should not trigger warnings there.
Artem Belevichbaae0932015-07-28 21:01:30 +00003254 Args.ClaimAllArgs(options::OPT_cuda_host_only);
Justin Lebardc3c5042016-04-19 02:27:07 +00003255 Args.ClaimAllArgs(options::OPT_cuda_compile_host_device);
Daniel Dunbar65229332009-03-13 11:38:42 +00003256}
3257
Artem Belevichecb178b2018-03-21 22:22:59 +00003258Action *Driver::ConstructPhaseAction(
3259 Compilation &C, const ArgList &Args, phases::ID Phase, Action *Input,
3260 Action::OffloadKind TargetDeviceOffloadKind) const {
Daniel Dunbar2608c542009-03-18 01:38:48 +00003261 llvm::PrettyStackTraceString CrashInfo("Constructing phase actions");
Samuel Antao64e965e2016-09-30 15:34:19 +00003262
3263 // Some types skip the assembler phase (e.g., llvm-bc), but we can't
3264 // encode this in the steps because the intermediate type depends on
3265 // arguments. Just special case here.
3266 if (Phase == phases::Assemble && Input->getType() != types::TY_PP_Asm)
3267 return Input;
3268
Daniel Dunbar65229332009-03-13 11:38:42 +00003269 // Build the appropriate action.
3270 switch (Phase) {
Douglas Katzmana67e50c2015-06-26 15:47:46 +00003271 case phases::Link:
3272 llvm_unreachable("link action invalid here.");
Daniel Dunbar65229332009-03-13 11:38:42 +00003273 case phases::Preprocess: {
Daniel Dunbard67a3222009-03-30 06:36:42 +00003274 types::ID OutputTy;
3275 // -{M, MM} alter the output type.
Daniel Dunbar86aed7d2010-12-08 21:33:40 +00003276 if (Args.hasArg(options::OPT_M, options::OPT_MM)) {
Daniel Dunbard67a3222009-03-30 06:36:42 +00003277 OutputTy = types::TY_Dependencies;
3278 } else {
David Blaikie5d577a22012-06-29 22:03:56 +00003279 OutputTy = Input->getType();
3280 if (!Args.hasFlag(options::OPT_frewrite_includes,
Justin Bognerce8245b2014-06-24 08:01:01 +00003281 options::OPT_fno_rewrite_includes, false) &&
Richard Smith86a3ef52017-06-09 21:24:02 +00003282 !Args.hasFlag(options::OPT_frewrite_imports,
3283 options::OPT_fno_rewrite_imports, false) &&
Justin Bognerce8245b2014-06-24 08:01:01 +00003284 !CCGenDiagnostics)
David Blaikie5d577a22012-06-29 22:03:56 +00003285 OutputTy = types::getPreprocessedType(OutputTy);
Daniel Dunbard67a3222009-03-30 06:36:42 +00003286 assert(OutputTy != types::TY_INVALID &&
3287 "Cannot preprocess this input type!");
3288 }
Justin Lebar41094612016-01-11 23:07:27 +00003289 return C.MakeAction<PreprocessJobAction>(Input, OutputTy);
Daniel Dunbar65229332009-03-13 11:38:42 +00003290 }
Aaron Ballman1f10cc52012-07-31 01:21:00 +00003291 case phases::Precompile: {
Richard Smithdd4ad3d2016-08-30 19:06:26 +00003292 types::ID OutputTy = getPrecompiledType(Input->getType());
3293 assert(OutputTy != types::TY_INVALID &&
3294 "Cannot precompile this input type!");
Richard Smithcd35eff2018-09-15 01:21:16 +00003295
3296 // If we're given a module name, precompile header file inputs as a
3297 // module, not as a precompiled header.
3298 const char *ModName = nullptr;
3299 if (OutputTy == types::TY_PCH) {
3300 if (Arg *A = Args.getLastArg(options::OPT_fmodule_name_EQ))
3301 ModName = A->getValue();
3302 if (ModName)
3303 OutputTy = types::TY_ModuleFile;
3304 }
3305
Aaron Ballman1f10cc52012-07-31 01:21:00 +00003306 if (Args.hasArg(options::OPT_fsyntax_only)) {
3307 // Syntax checks should not emit a PCH file
3308 OutputTy = types::TY_Nothing;
3309 }
Richard Smithcd35eff2018-09-15 01:21:16 +00003310
3311 if (ModName)
3312 return C.MakeAction<HeaderModulePrecompileJobAction>(Input, OutputTy,
3313 ModName);
Justin Lebar41094612016-01-11 23:07:27 +00003314 return C.MakeAction<PrecompileJobAction>(Input, OutputTy);
Aaron Ballman1f10cc52012-07-31 01:21:00 +00003315 }
Daniel Dunbar65229332009-03-13 11:38:42 +00003316 case phases::Compile: {
David Blaikie486f4402014-08-29 07:25:23 +00003317 if (Args.hasArg(options::OPT_fsyntax_only))
Justin Lebar41094612016-01-11 23:07:27 +00003318 return C.MakeAction<CompileJobAction>(Input, types::TY_Nothing);
David Blaikie486f4402014-08-29 07:25:23 +00003319 if (Args.hasArg(options::OPT_rewrite_objc))
Justin Lebar41094612016-01-11 23:07:27 +00003320 return C.MakeAction<CompileJobAction>(Input, types::TY_RewrittenObjC);
David Blaikie486f4402014-08-29 07:25:23 +00003321 if (Args.hasArg(options::OPT_rewrite_legacy_objc))
Justin Lebar41094612016-01-11 23:07:27 +00003322 return C.MakeAction<CompileJobAction>(Input,
3323 types::TY_RewrittenLegacyObjC);
David Blaikie486f4402014-08-29 07:25:23 +00003324 if (Args.hasArg(options::OPT__analyze, options::OPT__analyze_auto))
Justin Lebar41094612016-01-11 23:07:27 +00003325 return C.MakeAction<AnalyzeJobAction>(Input, types::TY_Plist);
David Blaikie486f4402014-08-29 07:25:23 +00003326 if (Args.hasArg(options::OPT__migrate))
Justin Lebar41094612016-01-11 23:07:27 +00003327 return C.MakeAction<MigrateJobAction>(Input, types::TY_Remap);
David Blaikie486f4402014-08-29 07:25:23 +00003328 if (Args.hasArg(options::OPT_emit_ast))
Justin Lebar41094612016-01-11 23:07:27 +00003329 return C.MakeAction<CompileJobAction>(Input, types::TY_AST);
David Blaikie486f4402014-08-29 07:25:23 +00003330 if (Args.hasArg(options::OPT_module_file_info))
Justin Lebar41094612016-01-11 23:07:27 +00003331 return C.MakeAction<CompileJobAction>(Input, types::TY_ModuleFile);
David Blaikie486f4402014-08-29 07:25:23 +00003332 if (Args.hasArg(options::OPT_verify_pch))
Justin Lebar41094612016-01-11 23:07:27 +00003333 return C.MakeAction<VerifyPCHJobAction>(Input, types::TY_Nothing);
3334 return C.MakeAction<CompileJobAction>(Input, types::TY_LLVM_BC);
Bob Wilson23a55f12014-12-21 07:00:00 +00003335 }
3336 case phases::Backend: {
Artem Belevichecb178b2018-03-21 22:22:59 +00003337 if (isUsingLTO() && TargetDeviceOffloadKind == Action::OFK_None) {
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00003338 types::ID Output =
Douglas Katzmana67e50c2015-06-26 15:47:46 +00003339 Args.hasArg(options::OPT_S) ? types::TY_LTO_IR : types::TY_LTO_BC;
Justin Lebar41094612016-01-11 23:07:27 +00003340 return C.MakeAction<BackendJobAction>(Input, Output);
David Blaikie486f4402014-08-29 07:25:23 +00003341 }
3342 if (Args.hasArg(options::OPT_emit_llvm)) {
Shuxin Yang4b3c7ff2013-08-23 21:34:57 +00003343 types::ID Output =
Douglas Katzmana67e50c2015-06-26 15:47:46 +00003344 Args.hasArg(options::OPT_S) ? types::TY_LLVM_IR : types::TY_LLVM_BC;
Justin Lebar41094612016-01-11 23:07:27 +00003345 return C.MakeAction<BackendJobAction>(Input, Output);
Daniel Dunbar65229332009-03-13 11:38:42 +00003346 }
Justin Lebar41094612016-01-11 23:07:27 +00003347 return C.MakeAction<BackendJobAction>(Input, types::TY_PP_Asm);
Daniel Dunbar65229332009-03-13 11:38:42 +00003348 }
3349 case phases::Assemble:
Justin Lebar21e5d4f2016-01-14 21:41:27 +00003350 return C.MakeAction<AssembleJobAction>(std::move(Input), types::TY_Object);
Daniel Dunbar65229332009-03-13 11:38:42 +00003351 }
3352
David Blaikie83d382b2011-09-23 05:06:16 +00003353 llvm_unreachable("invalid phase in ConstructPhaseAction");
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00003354}
3355
Daniel Dunbarf0eddb82009-03-18 02:55:38 +00003356void Driver::BuildJobs(Compilation &C) const {
Daniel Dunbar2608c542009-03-18 01:38:48 +00003357 llvm::PrettyStackTraceString CrashInfo("Building compilation jobs");
Daniel Dunbare75d8342009-03-16 06:56:51 +00003358
3359 Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o);
3360
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00003361 // It is an error to provide a -o option if we are making multiple output
3362 // files.
Daniel Dunbare75d8342009-03-16 06:56:51 +00003363 if (FinalOutput) {
3364 unsigned NumOutputs = 0;
Saleem Abdulrasoolda3f4e52014-12-29 21:02:47 +00003365 for (const Action *A : C.getActions())
3366 if (A->getType() != types::TY_Nothing)
Daniel Dunbare75d8342009-03-16 06:56:51 +00003367 ++NumOutputs;
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00003368
Daniel Dunbare75d8342009-03-16 06:56:51 +00003369 if (NumOutputs > 1) {
3370 Diag(clang::diag::err_drv_output_argument_with_multiple_files);
Craig Topper92fc2df2014-05-17 16:56:41 +00003371 FinalOutput = nullptr;
Daniel Dunbare75d8342009-03-16 06:56:51 +00003372 }
3373 }
3374
Chad Rosier35767232013-04-30 22:01:21 +00003375 // Collect the list of architectures.
3376 llvm::StringSet<> ArchNames;
Saleem Abdulrasool688b6bc2014-12-29 19:01:36 +00003377 if (C.getDefaultToolChain().getTriple().isOSBinFormatMachO())
3378 for (const Arg *A : C.getArgs())
Chad Rosier35767232013-04-30 22:01:21 +00003379 if (A->getOption().matches(options::OPT_arch))
3380 ArchNames.insert(A->getValue());
Chad Rosier35767232013-04-30 22:01:21 +00003381
Justin Lebarb44f6fe2016-01-14 21:41:21 +00003382 // Set of (Action, canonical ToolChain triple) pairs we've built jobs for.
3383 std::map<std::pair<const Action *, std::string>, InputInfo> CachedResults;
Saleem Abdulrasool688b6bc2014-12-29 19:01:36 +00003384 for (Action *A : C.getActions()) {
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00003385 // If we are linking an image for multiple archs then the linker wants
3386 // -arch_multiple and -final_output <final image name>. Unfortunately, this
3387 // doesn't fit in cleanly because we have to pass this information down.
Daniel Dunbare75d8342009-03-16 06:56:51 +00003388 //
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00003389 // FIXME: This is a hack; find a cleaner way to integrate this into the
3390 // process.
Craig Topper92fc2df2014-05-17 16:56:41 +00003391 const char *LinkingOutput = nullptr;
Daniel Dunbardd765242009-03-26 16:12:09 +00003392 if (isa<LipoJobAction>(A)) {
Daniel Dunbare75d8342009-03-16 06:56:51 +00003393 if (FinalOutput)
Richard Smithbd55daf2012-11-01 04:30:05 +00003394 LinkingOutput = FinalOutput->getValue();
Daniel Dunbare75d8342009-03-16 06:56:51 +00003395 else
Hans Wennborga7707222015-01-09 17:38:53 +00003396 LinkingOutput = getDefaultImageName();
Daniel Dunbare75d8342009-03-16 06:56:51 +00003397 }
3398
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00003399 BuildJobsForAction(C, A, &C.getDefaultToolChain(),
Mehdi Aminic50b1a22016-10-07 21:27:26 +00003400 /*BoundArch*/ StringRef(),
Daniel Dunbare75d8342009-03-16 06:56:51 +00003401 /*AtTopLevel*/ true,
Chad Rosier35767232013-04-30 22:01:21 +00003402 /*MultipleArchs*/ ArchNames.size() > 1,
Samuel Antaod06239d2016-07-15 23:13:27 +00003403 /*LinkingOutput*/ LinkingOutput, CachedResults,
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003404 /*TargetDeviceOffloadKind*/ Action::OFK_None);
Daniel Dunbare75d8342009-03-16 06:56:51 +00003405 }
Daniel Dunbar3ce436d2009-03-16 06:42:30 +00003406
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00003407 // If the user passed -Qunused-arguments or there were errors, don't warn
3408 // about any unused arguments.
Argyrios Kyrtzidis31448a42010-11-18 21:47:07 +00003409 if (Diags.hasErrorOccurred() ||
Daniel Dunbara3cfbe32009-04-07 19:04:18 +00003410 C.getArgs().hasArg(options::OPT_Qunused_arguments))
Daniel Dunbard175d972009-03-18 18:03:46 +00003411 return;
3412
Daniel Dunbar58399ae2009-03-29 22:24:54 +00003413 // Claim -### here.
Douglas Katzmana67e50c2015-06-26 15:47:46 +00003414 (void)C.getArgs().hasArg(options::OPT__HASH_HASH_HASH);
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00003415
Nico Weber47bf5052016-04-25 21:15:49 +00003416 // Claim --driver-mode, --rsp-quoting, it was handled earlier.
Douglas Katzmana67e50c2015-06-26 15:47:46 +00003417 (void)C.getArgs().hasArg(options::OPT_driver_mode);
Nico Weber47bf5052016-04-25 21:15:49 +00003418 (void)C.getArgs().hasArg(options::OPT_rsp_quoting);
Hans Wennborg70850d82013-07-18 20:29:38 +00003419
Saleem Abdulrasool688b6bc2014-12-29 19:01:36 +00003420 for (Arg *A : C.getArgs()) {
Daniel Dunbar3ce436d2009-03-16 06:42:30 +00003421 // FIXME: It would be nice to be able to send the argument to the
David Blaikie9c902b52011-09-25 23:23:43 +00003422 // DiagnosticsEngine, so that extra values, position, and so on could be
3423 // printed.
Daniel Dunbar90dd6f42009-04-04 00:52:26 +00003424 if (!A->isClaimed()) {
Michael J. Spencer66e2b202012-10-19 22:37:06 +00003425 if (A->getOption().hasFlag(options::NoArgumentUnused))
Daniel Dunbara3cfbe32009-04-07 19:04:18 +00003426 continue;
3427
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00003428 // Suppress the warning automatically if this is just a flag, and it is an
3429 // instance of an argument we already claimed.
Daniel Dunbar90dd6f42009-04-04 00:52:26 +00003430 const Option &Opt = A->getOption();
Michael J. Spencerad3ccc32012-08-20 21:41:17 +00003431 if (Opt.getKind() == Option::FlagClass) {
Daniel Dunbar90dd6f42009-04-04 00:52:26 +00003432 bool DuplicateClaimed = false;
3433
Sean Silva14facf32015-06-09 01:57:17 +00003434 for (const Arg *AA : C.getArgs().filtered(&Opt)) {
3435 if (AA->isClaimed()) {
Daniel Dunbar90dd6f42009-04-04 00:52:26 +00003436 DuplicateClaimed = true;
3437 break;
3438 }
3439 }
3440
3441 if (DuplicateClaimed)
3442 continue;
3443 }
3444
Ehsan Akhgarid8518332016-01-25 21:14:52 +00003445 // In clang-cl, don't mention unknown arguments here since they have
3446 // already been warned about.
3447 if (!IsCLMode() || !A->getOption().matches(options::OPT_UNKNOWN))
3448 Diag(clang::diag::warn_drv_unused_argument)
3449 << A->getAsString(C.getArgs());
Daniel Dunbar90dd6f42009-04-04 00:52:26 +00003450 }
Daniel Dunbar3ce436d2009-03-16 06:42:30 +00003451 }
Daniel Dunbar95e6b192009-03-13 22:12:33 +00003452}
Daniel Dunbarc4343942010-02-03 03:07:56 +00003453
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00003454namespace {
3455/// Utility class to control the collapse of dependent actions and select the
3456/// tools accordingly.
3457class ToolSelector final {
3458 /// The tool chain this selector refers to.
3459 const ToolChain &TC;
Daniel Dunbarf9ff3502010-05-14 02:03:00 +00003460
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00003461 /// The compilation this selector refers to.
3462 const Compilation &C;
Samuel Antaod06239d2016-07-15 23:13:27 +00003463
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00003464 /// The base action this selector refers to.
3465 const JobAction *BaseAction;
Samuel Antaod06239d2016-07-15 23:13:27 +00003466
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00003467 /// Set to true if the current toolchain refers to host actions.
3468 bool IsHostSelector;
Samuel Antaod06239d2016-07-15 23:13:27 +00003469
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00003470 /// Set to true if save-temps and embed-bitcode functionalities are active.
3471 bool SaveTemps;
3472 bool EmbedBitcode;
3473
3474 /// Get previous dependent action or null if that does not exist. If
3475 /// \a CanBeCollapsed is false, that action must be legal to collapse or
3476 /// null will be returned.
3477 const JobAction *getPrevDependentAction(const ActionList &Inputs,
3478 ActionList &SavedOffloadAction,
3479 bool CanBeCollapsed = true) {
3480 // An option can be collapsed only if it has a single input.
3481 if (Inputs.size() != 1)
Craig Topper92fc2df2014-05-17 16:56:41 +00003482 return nullptr;
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00003483
3484 Action *CurAction = *Inputs.begin();
3485 if (CanBeCollapsed &&
3486 !CurAction->isCollapsingWithNextDependentActionLegal())
3487 return nullptr;
3488
3489 // If the input action is an offload action. Look through it and save any
3490 // offload action that can be dropped in the event of a collapse.
3491 if (auto *OA = dyn_cast<OffloadAction>(CurAction)) {
3492 // If the dependent action is a device action, we will attempt to collapse
3493 // only with other device actions. Otherwise, we would do the same but
3494 // with host actions only.
3495 if (!IsHostSelector) {
3496 if (OA->hasSingleDeviceDependence(/*DoNotConsiderHostActions=*/true)) {
3497 CurAction =
3498 OA->getSingleDeviceDependence(/*DoNotConsiderHostActions=*/true);
3499 if (CanBeCollapsed &&
3500 !CurAction->isCollapsingWithNextDependentActionLegal())
3501 return nullptr;
3502 SavedOffloadAction.push_back(OA);
3503 return dyn_cast<JobAction>(CurAction);
3504 }
3505 } else if (OA->hasHostDependence()) {
3506 CurAction = OA->getHostDependence();
3507 if (CanBeCollapsed &&
3508 !CurAction->isCollapsingWithNextDependentActionLegal())
3509 return nullptr;
3510 SavedOffloadAction.push_back(OA);
3511 return dyn_cast<JobAction>(CurAction);
3512 }
3513 return nullptr;
3514 }
3515
3516 return dyn_cast<JobAction>(CurAction);
3517 }
3518
3519 /// Return true if an assemble action can be collapsed.
3520 bool canCollapseAssembleAction() const {
3521 return TC.useIntegratedAs() && !SaveTemps &&
3522 !C.getArgs().hasArg(options::OPT_via_file_asm) &&
3523 !C.getArgs().hasArg(options::OPT__SLASH_FA) &&
3524 !C.getArgs().hasArg(options::OPT__SLASH_Fa);
3525 }
3526
3527 /// Return true if a preprocessor action can be collapsed.
3528 bool canCollapsePreprocessorAction() const {
3529 return !C.getArgs().hasArg(options::OPT_no_integrated_cpp) &&
3530 !C.getArgs().hasArg(options::OPT_traditional_cpp) && !SaveTemps &&
3531 !C.getArgs().hasArg(options::OPT_rewrite_objc);
3532 }
3533
3534 /// Struct that relates an action with the offload actions that would be
3535 /// collapsed with it.
3536 struct JobActionInfo final {
3537 /// The action this info refers to.
3538 const JobAction *JA = nullptr;
3539 /// The offload actions we need to take care off if this action is
3540 /// collapsed.
3541 ActionList SavedOffloadAction;
3542 };
3543
3544 /// Append collapsed offload actions from the give nnumber of elements in the
3545 /// action info array.
3546 static void AppendCollapsedOffloadAction(ActionList &CollapsedOffloadAction,
3547 ArrayRef<JobActionInfo> &ActionInfo,
3548 unsigned ElementNum) {
3549 assert(ElementNum <= ActionInfo.size() && "Invalid number of elements.");
3550 for (unsigned I = 0; I < ElementNum; ++I)
3551 CollapsedOffloadAction.append(ActionInfo[I].SavedOffloadAction.begin(),
3552 ActionInfo[I].SavedOffloadAction.end());
3553 }
3554
3555 /// Functions that attempt to perform the combining. They detect if that is
3556 /// legal, and if so they update the inputs \a Inputs and the offload action
3557 /// that were collapsed in \a CollapsedOffloadAction. A tool that deals with
3558 /// the combined action is returned. If the combining is not legal or if the
3559 /// tool does not exist, null is returned.
3560 /// Currently three kinds of collapsing are supported:
3561 /// - Assemble + Backend + Compile;
3562 /// - Assemble + Backend ;
3563 /// - Backend + Compile.
3564 const Tool *
3565 combineAssembleBackendCompile(ArrayRef<JobActionInfo> ActionInfo,
Richard Smithcd35eff2018-09-15 01:21:16 +00003566 ActionList &Inputs,
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00003567 ActionList &CollapsedOffloadAction) {
3568 if (ActionInfo.size() < 3 || !canCollapseAssembleAction())
3569 return nullptr;
3570 auto *AJ = dyn_cast<AssembleJobAction>(ActionInfo[0].JA);
3571 auto *BJ = dyn_cast<BackendJobAction>(ActionInfo[1].JA);
3572 auto *CJ = dyn_cast<CompileJobAction>(ActionInfo[2].JA);
3573 if (!AJ || !BJ || !CJ)
3574 return nullptr;
3575
3576 // Get compiler tool.
3577 const Tool *T = TC.SelectTool(*CJ);
3578 if (!T)
3579 return nullptr;
3580
Steven Wu574b0f22016-03-01 01:07:58 +00003581 // When using -fembed-bitcode, it is required to have the same tool (clang)
3582 // for both CompilerJA and BackendJA. Otherwise, combine two stages.
3583 if (EmbedBitcode) {
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00003584 const Tool *BT = TC.SelectTool(*BJ);
3585 if (BT == T)
3586 return nullptr;
Steven Wu574b0f22016-03-01 01:07:58 +00003587 }
Bob Wilson23a55f12014-12-21 07:00:00 +00003588
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00003589 if (!T->hasIntegratedAssembler())
Bob Wilson23a55f12014-12-21 07:00:00 +00003590 return nullptr;
Samuel Antaod06239d2016-07-15 23:13:27 +00003591
Richard Smithcd35eff2018-09-15 01:21:16 +00003592 Inputs = CJ->getInputs();
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00003593 AppendCollapsedOffloadAction(CollapsedOffloadAction, ActionInfo,
3594 /*NumElements=*/3);
3595 return T;
3596 }
3597 const Tool *combineAssembleBackend(ArrayRef<JobActionInfo> ActionInfo,
Richard Smithcd35eff2018-09-15 01:21:16 +00003598 ActionList &Inputs,
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00003599 ActionList &CollapsedOffloadAction) {
3600 if (ActionInfo.size() < 2 || !canCollapseAssembleAction())
3601 return nullptr;
3602 auto *AJ = dyn_cast<AssembleJobAction>(ActionInfo[0].JA);
3603 auto *BJ = dyn_cast<BackendJobAction>(ActionInfo[1].JA);
3604 if (!AJ || !BJ)
3605 return nullptr;
3606
3607 // Retrieve the compile job, backend action must always be preceded by one.
3608 ActionList CompileJobOffloadActions;
3609 auto *CJ = getPrevDependentAction(BJ->getInputs(), CompileJobOffloadActions,
3610 /*CanBeCollapsed=*/false);
3611 if (!AJ || !BJ || !CJ)
3612 return nullptr;
3613
3614 assert(isa<CompileJobAction>(CJ) &&
3615 "Expecting compile job preceding backend job.");
3616
3617 // Get compiler tool.
3618 const Tool *T = TC.SelectTool(*CJ);
3619 if (!T)
3620 return nullptr;
3621
3622 if (!T->hasIntegratedAssembler())
3623 return nullptr;
3624
Richard Smithcd35eff2018-09-15 01:21:16 +00003625 Inputs = BJ->getInputs();
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00003626 AppendCollapsedOffloadAction(CollapsedOffloadAction, ActionInfo,
3627 /*NumElements=*/2);
3628 return T;
3629 }
3630 const Tool *combineBackendCompile(ArrayRef<JobActionInfo> ActionInfo,
Richard Smithcd35eff2018-09-15 01:21:16 +00003631 ActionList &Inputs,
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00003632 ActionList &CollapsedOffloadAction) {
Teresa Johnson9e4321c2018-04-17 16:39:25 +00003633 if (ActionInfo.size() < 2)
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00003634 return nullptr;
3635 auto *BJ = dyn_cast<BackendJobAction>(ActionInfo[0].JA);
3636 auto *CJ = dyn_cast<CompileJobAction>(ActionInfo[1].JA);
3637 if (!BJ || !CJ)
3638 return nullptr;
3639
Teresa Johnson9e4321c2018-04-17 16:39:25 +00003640 // Check if the initial input (to the compile job or its predessor if one
3641 // exists) is LLVM bitcode. In that case, no preprocessor step is required
3642 // and we can still collapse the compile and backend jobs when we have
3643 // -save-temps. I.e. there is no need for a separate compile job just to
3644 // emit unoptimized bitcode.
3645 bool InputIsBitcode = true;
3646 for (size_t i = 1; i < ActionInfo.size(); i++)
3647 if (ActionInfo[i].JA->getType() != types::TY_LLVM_BC &&
3648 ActionInfo[i].JA->getType() != types::TY_LTO_BC) {
3649 InputIsBitcode = false;
3650 break;
3651 }
3652 if (!InputIsBitcode && !canCollapsePreprocessorAction())
3653 return nullptr;
3654
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00003655 // Get compiler tool.
3656 const Tool *T = TC.SelectTool(*CJ);
3657 if (!T)
3658 return nullptr;
3659
Teresa Johnson9e4321c2018-04-17 16:39:25 +00003660 if (T->canEmitIR() && ((SaveTemps && !InputIsBitcode) || EmbedBitcode))
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00003661 return nullptr;
3662
Richard Smithcd35eff2018-09-15 01:21:16 +00003663 Inputs = CJ->getInputs();
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00003664 AppendCollapsedOffloadAction(CollapsedOffloadAction, ActionInfo,
3665 /*NumElements=*/2);
3666 return T;
3667 }
3668
3669 /// Updates the inputs if the obtained tool supports combining with
3670 /// preprocessor action, and the current input is indeed a preprocessor
3671 /// action. If combining results in the collapse of offloading actions, those
3672 /// are appended to \a CollapsedOffloadAction.
Richard Smithcd35eff2018-09-15 01:21:16 +00003673 void combineWithPreprocessor(const Tool *T, ActionList &Inputs,
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00003674 ActionList &CollapsedOffloadAction) {
3675 if (!T || !canCollapsePreprocessorAction() || !T->hasIntegratedCPP())
3676 return;
3677
3678 // Attempt to get a preprocessor action dependence.
3679 ActionList PreprocessJobOffloadActions;
Richard Smithcd35eff2018-09-15 01:21:16 +00003680 ActionList NewInputs;
3681 for (Action *A : Inputs) {
3682 auto *PJ = getPrevDependentAction({A}, PreprocessJobOffloadActions);
3683 if (!PJ || !isa<PreprocessJobAction>(PJ)) {
3684 NewInputs.push_back(A);
3685 continue;
3686 }
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00003687
Richard Smithcd35eff2018-09-15 01:21:16 +00003688 // This is legal to combine. Append any offload action we found and add the
3689 // current input to preprocessor inputs.
3690 CollapsedOffloadAction.append(PreprocessJobOffloadActions.begin(),
3691 PreprocessJobOffloadActions.end());
3692 NewInputs.append(PJ->input_begin(), PJ->input_end());
3693 }
3694 Inputs = NewInputs;
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00003695 }
3696
3697public:
3698 ToolSelector(const JobAction *BaseAction, const ToolChain &TC,
3699 const Compilation &C, bool SaveTemps, bool EmbedBitcode)
3700 : TC(TC), C(C), BaseAction(BaseAction), SaveTemps(SaveTemps),
3701 EmbedBitcode(EmbedBitcode) {
3702 assert(BaseAction && "Invalid base action.");
3703 IsHostSelector = BaseAction->getOffloadingDeviceKind() == Action::OFK_None;
3704 }
3705
3706 /// Check if a chain of actions can be combined and return the tool that can
3707 /// handle the combination of actions. The pointer to the current inputs \a
3708 /// Inputs and the list of offload actions \a CollapsedOffloadActions
3709 /// connected to collapsed actions are updated accordingly. The latter enables
3710 /// the caller of the selector to process them afterwards instead of just
3711 /// dropping them. If no suitable tool is found, null will be returned.
Richard Smithcd35eff2018-09-15 01:21:16 +00003712 const Tool *getTool(ActionList &Inputs,
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00003713 ActionList &CollapsedOffloadAction) {
3714 //
3715 // Get the largest chain of actions that we could combine.
3716 //
3717
3718 SmallVector<JobActionInfo, 5> ActionChain(1);
3719 ActionChain.back().JA = BaseAction;
3720 while (ActionChain.back().JA) {
3721 const Action *CurAction = ActionChain.back().JA;
3722
3723 // Grow the chain by one element.
3724 ActionChain.resize(ActionChain.size() + 1);
3725 JobActionInfo &AI = ActionChain.back();
3726
3727 // Attempt to fill it with the
3728 AI.JA =
3729 getPrevDependentAction(CurAction->getInputs(), AI.SavedOffloadAction);
Daniel Dunbarc4343942010-02-03 03:07:56 +00003730 }
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00003731
3732 // Pop the last action info as it could not be filled.
3733 ActionChain.pop_back();
3734
3735 //
3736 // Attempt to combine actions. If all combining attempts failed, just return
3737 // the tool of the provided action. At the end we attempt to combine the
3738 // action with any preprocessor action it may depend on.
3739 //
3740
3741 const Tool *T = combineAssembleBackendCompile(ActionChain, Inputs,
3742 CollapsedOffloadAction);
3743 if (!T)
3744 T = combineAssembleBackend(ActionChain, Inputs, CollapsedOffloadAction);
3745 if (!T)
3746 T = combineBackendCompile(ActionChain, Inputs, CollapsedOffloadAction);
3747 if (!T) {
Richard Smithcd35eff2018-09-15 01:21:16 +00003748 Inputs = BaseAction->getInputs();
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00003749 T = TC.SelectTool(*BaseAction);
3750 }
3751
3752 combineWithPreprocessor(T, Inputs, CollapsedOffloadAction);
3753 return T;
Daniel Dunbarc4343942010-02-03 03:07:56 +00003754 }
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00003755};
Daniel Dunbarc4343942010-02-03 03:07:56 +00003756}
3757
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003758/// Return a string that uniquely identifies the result of a job. The bound arch
3759/// is not necessarily represented in the toolchain's triple -- for example,
3760/// armv7 and armv7s both map to the same triple -- so we need both in our map.
3761/// Also, we need to add the offloading device kind, as the same tool chain can
3762/// be used for host and device for some programming models, e.g. OpenMP.
3763static std::string GetTriplePlusArchString(const ToolChain *TC,
3764 StringRef BoundArch,
3765 Action::OffloadKind OffloadKind) {
Justin Lebar55c83322016-01-16 03:30:08 +00003766 std::string TriplePlusArch = TC->getTriple().normalize();
Mehdi Aminic50b1a22016-10-07 21:27:26 +00003767 if (!BoundArch.empty()) {
Justin Lebar55c83322016-01-16 03:30:08 +00003768 TriplePlusArch += "-";
3769 TriplePlusArch += BoundArch;
3770 }
Samuel Antao59efaed2016-10-27 17:31:22 +00003771 TriplePlusArch += "-";
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003772 TriplePlusArch += Action::GetOffloadKindName(OffloadKind);
3773 return TriplePlusArch;
3774}
3775
3776InputInfo Driver::BuildJobsForAction(
3777 Compilation &C, const Action *A, const ToolChain *TC, StringRef BoundArch,
3778 bool AtTopLevel, bool MultipleArchs, const char *LinkingOutput,
3779 std::map<std::pair<const Action *, std::string>, InputInfo> &CachedResults,
3780 Action::OffloadKind TargetDeviceOffloadKind) const {
3781 std::pair<const Action *, std::string> ActionTC = {
3782 A, GetTriplePlusArchString(TC, BoundArch, TargetDeviceOffloadKind)};
Justin Lebarb44f6fe2016-01-14 21:41:21 +00003783 auto CachedResult = CachedResults.find(ActionTC);
3784 if (CachedResult != CachedResults.end()) {
3785 return CachedResult->second;
3786 }
Samuel Antaod06239d2016-07-15 23:13:27 +00003787 InputInfo Result = BuildJobsForActionNoCache(
3788 C, A, TC, BoundArch, AtTopLevel, MultipleArchs, LinkingOutput,
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003789 CachedResults, TargetDeviceOffloadKind);
Justin Lebarb44f6fe2016-01-14 21:41:21 +00003790 CachedResults[ActionTC] = Result;
3791 return Result;
3792}
3793
3794InputInfo Driver::BuildJobsForActionNoCache(
Mehdi Aminic50b1a22016-10-07 21:27:26 +00003795 Compilation &C, const Action *A, const ToolChain *TC, StringRef BoundArch,
Justin Lebarb44f6fe2016-01-14 21:41:21 +00003796 bool AtTopLevel, bool MultipleArchs, const char *LinkingOutput,
Samuel Antaod06239d2016-07-15 23:13:27 +00003797 std::map<std::pair<const Action *, std::string>, InputInfo> &CachedResults,
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003798 Action::OffloadKind TargetDeviceOffloadKind) const {
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00003799 llvm::PrettyStackTraceString CrashInfo("Building compilation jobs");
Daniel Dunbarc4acf9d2009-03-18 23:18:19 +00003800
Samuel Antaod06239d2016-07-15 23:13:27 +00003801 InputInfoList OffloadDependencesInputInfo;
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003802 bool BuildingForOffloadDevice = TargetDeviceOffloadKind != Action::OFK_None;
Samuel Antaod06239d2016-07-15 23:13:27 +00003803 if (const OffloadAction *OA = dyn_cast<OffloadAction>(A)) {
Alex Lorenz4003a982017-08-08 11:22:21 +00003804 // The 'Darwin' toolchain is initialized only when its arguments are
3805 // computed. Get the default arguments for OFK_None to ensure that
3806 // initialization is performed before processing the offload action.
3807 // FIXME: Remove when darwin's toolchain is initialized during construction.
3808 C.getArgsForToolChain(TC, BoundArch, Action::OFK_None);
3809
Samuel Antaod06239d2016-07-15 23:13:27 +00003810 // The offload action is expected to be used in four different situations.
3811 //
3812 // a) Set a toolchain/architecture/kind for a host action:
3813 // Host Action 1 -> OffloadAction -> Host Action 2
3814 //
3815 // b) Set a toolchain/architecture/kind for a device action;
3816 // Device Action 1 -> OffloadAction -> Device Action 2
3817 //
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00003818 // c) Specify a device dependence to a host action;
Samuel Antaod06239d2016-07-15 23:13:27 +00003819 // Device Action 1 _
3820 // \
3821 // Host Action 1 ---> OffloadAction -> Host Action 2
3822 //
3823 // d) Specify a host dependence to a device action.
3824 // Host Action 1 _
3825 // \
3826 // Device Action 1 ---> OffloadAction -> Device Action 2
3827 //
3828 // For a) and b), we just return the job generated for the dependence. For
3829 // c) and d) we override the current action with the host/device dependence
3830 // if the current toolchain is host/device and set the offload dependences
3831 // info with the jobs obtained from the device/host dependence(s).
3832
3833 // If there is a single device option, just generate the job for it.
3834 if (OA->hasSingleDeviceDependence()) {
3835 InputInfo DevA;
3836 OA->doOnEachDeviceDependence([&](Action *DepA, const ToolChain *DepTC,
3837 const char *DepBoundArch) {
3838 DevA =
3839 BuildJobsForAction(C, DepA, DepTC, DepBoundArch, AtTopLevel,
3840 /*MultipleArchs*/ !!DepBoundArch, LinkingOutput,
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003841 CachedResults, DepA->getOffloadingDeviceKind());
Samuel Antaod06239d2016-07-15 23:13:27 +00003842 });
3843 return DevA;
Artem Belevich0ff05cd2015-07-13 23:27:56 +00003844 }
Samuel Antaod06239d2016-07-15 23:13:27 +00003845
3846 // If 'Action 2' is host, we generate jobs for the device dependences and
3847 // override the current action with the host dependence. Otherwise, we
3848 // generate the host dependences and override the action with the device
3849 // dependence. The dependences can't therefore be a top-level action.
3850 OA->doOnEachDependence(
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003851 /*IsHostDependence=*/BuildingForOffloadDevice,
Samuel Antaod06239d2016-07-15 23:13:27 +00003852 [&](Action *DepA, const ToolChain *DepTC, const char *DepBoundArch) {
3853 OffloadDependencesInputInfo.push_back(BuildJobsForAction(
3854 C, DepA, DepTC, DepBoundArch, /*AtTopLevel=*/false,
3855 /*MultipleArchs*/ !!DepBoundArch, LinkingOutput, CachedResults,
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003856 DepA->getOffloadingDeviceKind()));
Samuel Antaod06239d2016-07-15 23:13:27 +00003857 });
3858
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003859 A = BuildingForOffloadDevice
Samuel Antaod06239d2016-07-15 23:13:27 +00003860 ? OA->getSingleDeviceDependence(/*DoNotConsiderHostActions=*/true)
3861 : OA->getHostDependence();
Artem Belevich0ff05cd2015-07-13 23:27:56 +00003862 }
3863
Daniel Dunbare75d8342009-03-16 06:56:51 +00003864 if (const InputAction *IA = dyn_cast<InputAction>(A)) {
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00003865 // FIXME: It would be nice to not claim this here; maybe the old scheme of
3866 // just using Args was better?
Daniel Dunbar5cdf3e02009-03-19 07:29:38 +00003867 const Arg &Input = IA->getInputArg();
3868 Input.claim();
Daniel Dunbar35cbfeb2010-06-09 22:31:08 +00003869 if (Input.getOption().matches(options::OPT_INPUT)) {
Richard Smithbd55daf2012-11-01 04:30:05 +00003870 const char *Name = Input.getValue();
Justin Lebard98cea82016-01-11 23:15:21 +00003871 return InputInfo(A, Name, /* BaseInput = */ Name);
Douglas Katzman678d0cb2015-06-16 18:01:24 +00003872 }
Justin Lebard98cea82016-01-11 23:15:21 +00003873 return InputInfo(A, &Input, /* BaseInput = */ "");
Daniel Dunbare75d8342009-03-16 06:56:51 +00003874 }
3875
3876 if (const BindArchAction *BAA = dyn_cast<BindArchAction>(A)) {
Chad Rosiera78a6eb2012-04-27 16:50:38 +00003877 const ToolChain *TC;
Mehdi Aminic50b1a22016-10-07 21:27:26 +00003878 StringRef ArchName = BAA->getArchName();
Daniel Dunbar1ef3f2a2009-09-08 23:37:19 +00003879
Mehdi Aminic50b1a22016-10-07 21:27:26 +00003880 if (!ArchName.empty())
Andrey Turetskiy6a8b91d2016-04-21 10:16:48 +00003881 TC = &getToolChain(C.getArgs(),
Petr Hosekdd38d932018-05-29 22:35:39 +00003882 computeTargetTriple(*this, TargetTriple,
Andrey Turetskiy6a8b91d2016-04-21 10:16:48 +00003883 C.getArgs(), ArchName));
Chad Rosiera78a6eb2012-04-27 16:50:38 +00003884 else
3885 TC = &C.getDefaultToolChain();
Daniel Dunbar1ef3f2a2009-09-08 23:37:19 +00003886
Nico Weber5a459f82016-02-23 19:30:43 +00003887 return BuildJobsForAction(C, *BAA->input_begin(), TC, ArchName, AtTopLevel,
Samuel Antaod06239d2016-07-15 23:13:27 +00003888 MultipleArchs, LinkingOutput, CachedResults,
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003889 TargetDeviceOffloadKind);
Daniel Dunbare75d8342009-03-16 06:56:51 +00003890 }
3891
Artem Belevich0ff05cd2015-07-13 23:27:56 +00003892
Richard Smithcd35eff2018-09-15 01:21:16 +00003893 ActionList Inputs = A->getInputs();
Daniel Dunbarc4343942010-02-03 03:07:56 +00003894
3895 const JobAction *JA = cast<JobAction>(A);
Samuel Antaod06239d2016-07-15 23:13:27 +00003896 ActionList CollapsedOffloadActions;
3897
Mehdi Amini6683e222017-01-24 18:12:25 +00003898 ToolSelector TS(JA, *TC, C, isSaveTempsEnabled(),
3899 embedBitcodeInObject() && !isUsingLTO());
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00003900 const Tool *T = TS.getTool(Inputs, CollapsedOffloadActions);
3901
Rafael Espindola79764462013-03-24 15:06:53 +00003902 if (!T)
Justin Lebar9eaa4892016-01-11 23:09:32 +00003903 return InputInfo();
Daniel Dunbare75d8342009-03-16 06:56:51 +00003904
Samuel Antaod06239d2016-07-15 23:13:27 +00003905 // If we've collapsed action list that contained OffloadAction we
3906 // need to build jobs for host/device-side inputs it may have held.
3907 for (const auto *OA : CollapsedOffloadActions)
3908 cast<OffloadAction>(OA)->doOnEachDependence(
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003909 /*IsHostDependence=*/BuildingForOffloadDevice,
Samuel Antaod06239d2016-07-15 23:13:27 +00003910 [&](Action *DepA, const ToolChain *DepTC, const char *DepBoundArch) {
3911 OffloadDependencesInputInfo.push_back(BuildJobsForAction(
Artem Belevichbee2f412016-08-22 18:50:34 +00003912 C, DepA, DepTC, DepBoundArch, /* AtTopLevel */ false,
Samuel Antaod06239d2016-07-15 23:13:27 +00003913 /*MultipleArchs=*/!!DepBoundArch, LinkingOutput, CachedResults,
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003914 DepA->getOffloadingDeviceKind()));
Samuel Antaod06239d2016-07-15 23:13:27 +00003915 });
Artem Belevichf8144ab2015-08-27 18:10:41 +00003916
Daniel Dunbare75d8342009-03-16 06:56:51 +00003917 // Only use pipes when there is exactly one input.
Daniel Dunbar1a093d22009-03-18 06:00:36 +00003918 InputInfoList InputInfos;
Richard Smithcd35eff2018-09-15 01:21:16 +00003919 for (const Action *Input : Inputs) {
Eric Christopher14668dd2013-02-18 00:38:25 +00003920 // Treat dsymutil and verify sub-jobs as being at the top-level too, they
3921 // shouldn't get temporary output names.
Daniel Dunbar6beaf512010-06-04 18:28:41 +00003922 // FIXME: Clean this up.
Justin Lebar9eaa4892016-01-11 23:09:32 +00003923 bool SubJobAtTopLevel =
3924 AtTopLevel && (isa<DsymutilJobAction>(A) || isa<VerifyJobAction>(A));
Samuel Antaod06239d2016-07-15 23:13:27 +00003925 InputInfos.push_back(BuildJobsForAction(
3926 C, Input, TC, BoundArch, SubJobAtTopLevel, MultipleArchs, LinkingOutput,
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003927 CachedResults, A->getOffloadingDeviceKind()));
Daniel Dunbare75d8342009-03-16 06:56:51 +00003928 }
3929
Daniel Dunbare75d8342009-03-16 06:56:51 +00003930 // Always use the first input as the base input.
3931 const char *BaseInput = InputInfos[0].getBaseInput();
Daniel Dunbar7a178a42009-03-17 17:53:55 +00003932
Daniel Dunbar6beaf512010-06-04 18:28:41 +00003933 // ... except dsymutil actions, which use their actual input as the base
3934 // input.
3935 if (JA->getType() == types::TY_dSYM)
3936 BaseInput = InputInfos[0].getFilename();
3937
Richard Smithcd35eff2018-09-15 01:21:16 +00003938 // ... and in header module compilations, which use the module name.
3939 if (auto *ModuleJA = dyn_cast<HeaderModulePrecompileJobAction>(JA))
3940 BaseInput = ModuleJA->getModuleName();
3941
Samuel Antaod06239d2016-07-15 23:13:27 +00003942 // Append outputs of offload device jobs to the input list
3943 if (!OffloadDependencesInputInfo.empty())
3944 InputInfos.append(OffloadDependencesInputInfo.begin(),
3945 OffloadDependencesInputInfo.end());
Artem Belevich0ff05cd2015-07-13 23:27:56 +00003946
Vedant Kumar18286cf2016-07-27 23:02:20 +00003947 // Set the effective triple of the toolchain for the duration of this job.
3948 llvm::Triple EffectiveTriple;
3949 const ToolChain &ToolTC = T->getToolChain();
Samuel Antao31fef982016-10-27 17:39:44 +00003950 const ArgList &Args =
3951 C.getArgsForToolChain(TC, BoundArch, A->getOffloadingDeviceKind());
Vedant Kumar18286cf2016-07-27 23:02:20 +00003952 if (InputInfos.size() != 1) {
3953 EffectiveTriple = llvm::Triple(ToolTC.ComputeEffectiveClangTriple(Args));
3954 } else {
3955 // Pass along the input type if it can be unambiguously determined.
3956 EffectiveTriple = llvm::Triple(
3957 ToolTC.ComputeEffectiveClangTriple(Args, InputInfos[0].getType()));
3958 }
3959 RegisterEffectiveTriple TripleRAII(ToolTC, EffectiveTriple);
3960
Daniel Dunbard00272f2010-08-02 02:38:15 +00003961 // Determine the place to write output to, if any.
Justin Lebar9eaa4892016-01-11 23:09:32 +00003962 InputInfo Result;
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003963 InputInfoList UnbundlingResults;
3964 if (auto *UA = dyn_cast<OffloadUnbundlingJobAction>(JA)) {
3965 // If we have an unbundling job, we need to create results for all the
3966 // outputs. We also update the results cache so that other actions using
3967 // this unbundling action can get the right results.
3968 for (auto &UI : UA->getDependentActionsInfo()) {
3969 assert(UI.DependentOffloadKind != Action::OFK_None &&
3970 "Unbundling with no offloading??");
3971
3972 // Unbundling actions are never at the top level. When we generate the
3973 // offloading prefix, we also do that for the host file because the
3974 // unbundling action does not change the type of the output which can
3975 // cause a overwrite.
3976 std::string OffloadingPrefix = Action::GetOffloadingFileNamePrefix(
3977 UI.DependentOffloadKind,
3978 UI.DependentToolChain->getTriple().normalize(),
3979 /*CreatePrefixForHost=*/true);
3980 auto CurI = InputInfo(
Yaxun Liu609f7522018-05-11 19:02:18 +00003981 UA,
3982 GetNamedOutputPath(C, *UA, BaseInput, UI.DependentBoundArch,
3983 /*AtTopLevel=*/false,
3984 MultipleArchs ||
3985 UI.DependentOffloadKind == Action::OFK_HIP,
3986 OffloadingPrefix),
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003987 BaseInput);
3988 // Save the unbundling result.
3989 UnbundlingResults.push_back(CurI);
3990
3991 // Get the unique string identifier for this dependence and cache the
3992 // result.
Yaxun Liu470b8332018-06-06 19:44:10 +00003993 StringRef Arch;
3994 if (TargetDeviceOffloadKind == Action::OFK_HIP) {
3995 if (UI.DependentOffloadKind == Action::OFK_Host)
Yaxun Liuf37b50a2018-07-24 01:03:44 +00003996 Arch = StringRef();
Yaxun Liu470b8332018-06-06 19:44:10 +00003997 else
3998 Arch = UI.DependentBoundArch;
3999 } else
4000 Arch = BoundArch;
4001
4002 CachedResults[{A, GetTriplePlusArchString(UI.DependentToolChain, Arch,
4003 UI.DependentOffloadKind)}] =
4004 CurI;
Samuel Antao3b7e38b2016-10-27 18:14:55 +00004005 }
4006
4007 // Now that we have all the results generated, select the one that should be
4008 // returned for the current depending action.
4009 std::pair<const Action *, std::string> ActionTC = {
4010 A, GetTriplePlusArchString(TC, BoundArch, TargetDeviceOffloadKind)};
4011 assert(CachedResults.find(ActionTC) != CachedResults.end() &&
4012 "Result does not exist??");
4013 Result = CachedResults[ActionTC];
4014 } else if (JA->getType() == types::TY_Nothing)
Justin Lebard98cea82016-01-11 23:15:21 +00004015 Result = InputInfo(A, BaseInput);
Samuel Antao3b7e38b2016-10-27 18:14:55 +00004016 else {
4017 // We only have to generate a prefix for the host if this is not a top-level
4018 // action.
4019 std::string OffloadingPrefix = Action::GetOffloadingFileNamePrefix(
4020 A->getOffloadingDeviceKind(), TC->getTriple().normalize(),
4021 /*CreatePrefixForHost=*/!!A->getOffloadingHostActiveKinds() &&
4022 !AtTopLevel);
Justin Lebard98cea82016-01-11 23:15:21 +00004023 Result = InputInfo(A, GetNamedOutputPath(C, *JA, BaseInput, BoundArch,
Samuel Antaod06239d2016-07-15 23:13:27 +00004024 AtTopLevel, MultipleArchs,
Samuel Antao3b7e38b2016-10-27 18:14:55 +00004025 OffloadingPrefix),
Justin Lebard98cea82016-01-11 23:15:21 +00004026 BaseInput);
Samuel Antao3b7e38b2016-10-27 18:14:55 +00004027 }
Daniel Dunbar7a178a42009-03-17 17:53:55 +00004028
Chad Rosierbe10f982011-08-02 17:58:04 +00004029 if (CCCPrintBindings && !CCGenDiagnostics) {
Rafael Espindola79764462013-03-24 15:06:53 +00004030 llvm::errs() << "# \"" << T->getToolChain().getTripleString() << '"'
4031 << " - \"" << T->getName() << "\", inputs: [";
Daniel Dunbarb39cc522009-03-17 22:47:06 +00004032 for (unsigned i = 0, e = InputInfos.size(); i != e; ++i) {
4033 llvm::errs() << InputInfos[i].getAsString();
4034 if (i + 1 != e)
4035 llvm::errs() << ", ";
4036 }
Samuel Antao3b7e38b2016-10-27 18:14:55 +00004037 if (UnbundlingResults.empty())
4038 llvm::errs() << "], output: " << Result.getAsString() << "\n";
4039 else {
4040 llvm::errs() << "], outputs: [";
4041 for (unsigned i = 0, e = UnbundlingResults.size(); i != e; ++i) {
4042 llvm::errs() << UnbundlingResults[i].getAsString();
4043 if (i + 1 != e)
4044 llvm::errs() << ", ";
4045 }
4046 llvm::errs() << "] \n";
4047 }
Daniel Dunbarb39cc522009-03-17 22:47:06 +00004048 } else {
Samuel Antao3b7e38b2016-10-27 18:14:55 +00004049 if (UnbundlingResults.empty())
4050 T->ConstructJob(
4051 C, *JA, Result, InputInfos,
4052 C.getArgsForToolChain(TC, BoundArch, JA->getOffloadingDeviceKind()),
4053 LinkingOutput);
4054 else
Samuel Antao7108bf32016-11-03 15:41:50 +00004055 T->ConstructJobMultipleOutputs(
Samuel Antao3b7e38b2016-10-27 18:14:55 +00004056 C, *JA, UnbundlingResults, InputInfos,
4057 C.getArgsForToolChain(TC, BoundArch, JA->getOffloadingDeviceKind()),
4058 LinkingOutput);
Daniel Dunbarb39cc522009-03-17 22:47:06 +00004059 }
Justin Lebar9eaa4892016-01-11 23:09:32 +00004060 return Result;
Daniel Dunbare75d8342009-03-16 06:56:51 +00004061}
4062
Hans Wennborga7707222015-01-09 17:38:53 +00004063const char *Driver::getDefaultImageName() const {
Petr Hosekdd38d932018-05-29 22:35:39 +00004064 llvm::Triple Target(llvm::Triple::normalize(TargetTriple));
Hans Wennborga7707222015-01-09 17:38:53 +00004065 return Target.isOSWindows() ? "a.exe" : "a.out";
4066}
4067
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004068/// Create output filename based on ArgValue, which could either be a
Hans Wennborg2c21f742013-10-17 16:16:23 +00004069/// full filename, filename without extension, or a directory. If ArgValue
4070/// does not provide a filename, then use BaseName, and use the extension
4071/// suitable for FileType.
Hans Wennborg207fcf02013-08-12 21:56:42 +00004072static const char *MakeCLOutputFilename(const ArgList &Args, StringRef ArgValue,
Douglas Katzmana67e50c2015-06-26 15:47:46 +00004073 StringRef BaseName,
4074 types::ID FileType) {
Hans Wennborg207fcf02013-08-12 21:56:42 +00004075 SmallString<128> Filename = ArgValue;
Justin Bogner5aaf2e72014-06-26 20:59:36 +00004076
Hans Wennborgf1a74252013-09-10 20:18:04 +00004077 if (ArgValue.empty()) {
4078 // If the argument is empty, output to BaseName in the current dir.
4079 Filename = BaseName;
4080 } else if (llvm::sys::path::is_separator(Filename.back())) {
Hans Wennborg207fcf02013-08-12 21:56:42 +00004081 // If the argument is a directory, output to BaseName in that dir.
4082 llvm::sys::path::append(Filename, BaseName);
4083 }
4084
4085 if (!llvm::sys::path::has_extension(ArgValue)) {
4086 // If the argument didn't provide an extension, then set it.
4087 const char *Extension = types::getTypeTempSuffix(FileType, true);
Hans Wennborgf1a74252013-09-10 20:18:04 +00004088
4089 if (FileType == types::TY_Image &&
4090 Args.hasArg(options::OPT__SLASH_LD, options::OPT__SLASH_LDd)) {
4091 // The output file is a dll.
4092 Extension = "dll";
4093 }
4094
Hans Wennborg207fcf02013-08-12 21:56:42 +00004095 llvm::sys::path::replace_extension(Filename, Extension);
4096 }
4097
4098 return Args.MakeArgString(Filename.c_str());
4099}
4100
Douglas Katzmana67e50c2015-06-26 15:47:46 +00004101const char *Driver::GetNamedOutputPath(Compilation &C, const JobAction &JA,
Daniel Dunbar7a178a42009-03-17 17:53:55 +00004102 const char *BaseInput,
Mehdi Aminic50b1a22016-10-07 21:27:26 +00004103 StringRef BoundArch, bool AtTopLevel,
Samuel Antaod06239d2016-07-15 23:13:27 +00004104 bool MultipleArchs,
Samuel Antao3b7e38b2016-10-27 18:14:55 +00004105 StringRef OffloadingPrefix) const {
Daniel Dunbar2608c542009-03-18 01:38:48 +00004106 llvm::PrettyStackTraceString CrashInfo("Computing output path");
Daniel Dunbar7a178a42009-03-17 17:53:55 +00004107 // Output to a user requested destination?
Douglas Katzmana67e50c2015-06-26 15:47:46 +00004108 if (AtTopLevel && !isa<DsymutilJobAction>(JA) && !isa<VerifyJobAction>(JA)) {
Daniel Dunbar7a178a42009-03-17 17:53:55 +00004109 if (Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o))
Chad Rosier633dcdc2013-01-24 19:14:47 +00004110 return C.addResultFile(FinalOutput->getValue(), &JA);
Daniel Dunbar7a178a42009-03-17 17:53:55 +00004111 }
4112
Hans Wennborge0053472013-12-20 18:40:46 +00004113 // For /P, preprocess to file named after BaseInput.
4114 if (C.getArgs().hasArg(options::OPT__SLASH_P)) {
4115 assert(AtTopLevel && isa<PreprocessJobAction>(JA));
4116 StringRef BaseName = llvm::sys::path::filename(BaseInput);
Hans Wennborg04c764f2014-06-17 00:19:12 +00004117 StringRef NameArg;
Greg Bedwell065f70a2015-06-09 10:24:06 +00004118 if (Arg *A = C.getArgs().getLastArg(options::OPT__SLASH_Fi))
Hans Wennborg04c764f2014-06-17 00:19:12 +00004119 NameArg = A->getValue();
Douglas Katzmana67e50c2015-06-26 15:47:46 +00004120 return C.addResultFile(
4121 MakeCLOutputFilename(C.getArgs(), NameArg, BaseName, types::TY_PP_C),
4122 &JA);
Hans Wennborge0053472013-12-20 18:40:46 +00004123 }
4124
Nick Lewycky6e1ce292010-09-24 00:46:53 +00004125 // Default to writing to stdout?
David Blaikiebc023c92018-06-14 23:09:06 +00004126 if (AtTopLevel && !CCGenDiagnostics && isa<PreprocessJobAction>(JA))
Nick Lewycky6e1ce292010-09-24 00:46:53 +00004127 return "-";
4128
Hans Wennborg2c21f742013-10-17 16:16:23 +00004129 // Is this the assembly listing for /FA?
4130 if (JA.getType() == types::TY_PP_Asm &&
4131 (C.getArgs().hasArg(options::OPT__SLASH_FA) ||
4132 C.getArgs().hasArg(options::OPT__SLASH_Fa))) {
4133 // Use /Fa and the input filename to determine the asm file name.
4134 StringRef BaseName = llvm::sys::path::filename(BaseInput);
4135 StringRef FaValue = C.getArgs().getLastArgValue(options::OPT__SLASH_Fa);
Douglas Katzmana67e50c2015-06-26 15:47:46 +00004136 return C.addResultFile(
4137 MakeCLOutputFilename(C.getArgs(), FaValue, BaseName, JA.getType()),
4138 &JA);
Hans Wennborg2c21f742013-10-17 16:16:23 +00004139 }
4140
Daniel Dunbar7a178a42009-03-17 17:53:55 +00004141 // Output to a temporary file?
Reid Kleckner68eb60b2015-02-02 22:41:48 +00004142 if ((!AtTopLevel && !isSaveTempsEnabled() &&
Douglas Katzmana67e50c2015-06-26 15:47:46 +00004143 !C.getArgs().hasArg(options::OPT__SLASH_Fo)) ||
Chad Rosierbe10f982011-08-02 17:58:04 +00004144 CCGenDiagnostics) {
Chad Rosier97c37372011-08-26 22:27:02 +00004145 StringRef Name = llvm::sys::path::filename(BaseInput);
4146 std::pair<StringRef, StringRef> Split = Name.split('.');
Bob Haarman7e4d3ff2018-07-09 21:07:20 +00004147 SmallString<128> TmpName;
4148 const char *Suffix = types::getTypeTempSuffix(JA.getType(), IsCLMode());
4149 Arg *A = C.getArgs().getLastArg(options::OPT_fcrash_diagnostics_dir);
4150 if (CCGenDiagnostics && A) {
4151 SmallString<128> CrashDirectory(A->getValue());
4152 llvm::sys::path::append(CrashDirectory, Split.first);
4153 const char *Middle = Suffix ? "-%%%%%%." : "-%%%%%%";
4154 std::error_code EC =
4155 llvm::sys::fs::createUniqueFile(CrashDirectory + Middle + Suffix, TmpName);
4156 if (EC) {
4157 Diag(clang::diag::err_unable_to_make_temp) << EC.message();
4158 return "";
4159 }
4160 } else {
4161 TmpName = GetTemporaryPath(Split.first, Suffix);
4162 }
Malcolm Parsonsf76f6502016-11-02 10:39:27 +00004163 return C.addTempFile(C.getArgs().MakeArgString(TmpName));
Daniel Dunbar7a178a42009-03-17 17:53:55 +00004164 }
4165
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00004166 SmallString<128> BasePath(BaseInput);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004167 StringRef BaseName;
Daniel Dunbar67fea712011-03-25 18:16:51 +00004168
4169 // Dsymutil actions should use the full path.
Eric Christopher551ef452011-08-23 17:56:55 +00004170 if (isa<DsymutilJobAction>(JA) || isa<VerifyJobAction>(JA))
Daniel Dunbar67fea712011-03-25 18:16:51 +00004171 BaseName = BasePath;
4172 else
4173 BaseName = llvm::sys::path::filename(BasePath);
Daniel Dunbar7a178a42009-03-17 17:53:55 +00004174
4175 // Determine what the derived output name should be.
4176 const char *NamedOutput;
Hans Wennborg2b89a262013-08-06 22:11:28 +00004177
Hans Wennborg625fba82016-10-04 21:01:04 +00004178 if ((JA.getType() == types::TY_Object || JA.getType() == types::TY_LTO_BC) &&
Ehsan Akhgari81f36b72014-09-11 18:16:21 +00004179 C.getArgs().hasArg(options::OPT__SLASH_Fo, options::OPT__SLASH_o)) {
4180 // The /Fo or /o flag decides the object filename.
Douglas Katzmana67e50c2015-06-26 15:47:46 +00004181 StringRef Val =
4182 C.getArgs()
4183 .getLastArg(options::OPT__SLASH_Fo, options::OPT__SLASH_o)
4184 ->getValue();
4185 NamedOutput =
4186 MakeCLOutputFilename(C.getArgs(), Val, BaseName, types::TY_Object);
Hans Wennborg207fcf02013-08-12 21:56:42 +00004187 } else if (JA.getType() == types::TY_Image &&
Douglas Katzmana67e50c2015-06-26 15:47:46 +00004188 C.getArgs().hasArg(options::OPT__SLASH_Fe,
4189 options::OPT__SLASH_o)) {
Ehsan Akhgari81f36b72014-09-11 18:16:21 +00004190 // The /Fe or /o flag names the linked file.
Douglas Katzmana67e50c2015-06-26 15:47:46 +00004191 StringRef Val =
4192 C.getArgs()
4193 .getLastArg(options::OPT__SLASH_Fe, options::OPT__SLASH_o)
4194 ->getValue();
4195 NamedOutput =
4196 MakeCLOutputFilename(C.getArgs(), Val, BaseName, types::TY_Image);
Hans Wennborgf1a74252013-09-10 20:18:04 +00004197 } else if (JA.getType() == types::TY_Image) {
Hans Wennborg207fcf02013-08-12 21:56:42 +00004198 if (IsCLMode()) {
4199 // clang-cl uses BaseName for the executable name.
Douglas Katzmana67e50c2015-06-26 15:47:46 +00004200 NamedOutput =
4201 MakeCLOutputFilename(C.getArgs(), "", BaseName, types::TY_Image);
Samuel Antao59efaed2016-10-27 17:31:22 +00004202 } else {
Hans Wennborga7707222015-01-09 17:38:53 +00004203 SmallString<128> Output(getDefaultImageName());
Samuel Antao3b7e38b2016-10-27 18:14:55 +00004204 Output += OffloadingPrefix;
Samuel Antao59efaed2016-10-27 17:31:22 +00004205 if (MultipleArchs && !BoundArch.empty()) {
4206 Output += "-";
4207 Output.append(BoundArch);
4208 }
Chad Rosier35767232013-04-30 22:01:21 +00004209 NamedOutput = C.getArgs().MakeArgString(Output.c_str());
Nico Weber2ca4be92016-03-01 23:16:44 +00004210 }
4211 } else if (JA.getType() == types::TY_PCH && IsCLMode()) {
Malcolm Parsonsf76f6502016-11-02 10:39:27 +00004212 NamedOutput = C.getArgs().MakeArgString(GetClPchPath(C, BaseName));
Daniel Dunbar7a178a42009-03-17 17:53:55 +00004213 } else {
Hans Wennborg0a096a02013-09-05 17:05:56 +00004214 const char *Suffix = types::getTypeTempSuffix(JA.getType(), IsCLMode());
Daniel Dunbar7a178a42009-03-17 17:53:55 +00004215 assert(Suffix && "All types used for output should have a suffix.");
4216
4217 std::string::size_type End = std::string::npos;
4218 if (!types::appendSuffixForType(JA.getType()))
4219 End = BaseName.rfind('.');
Chad Rosier35767232013-04-30 22:01:21 +00004220 SmallString<128> Suffixed(BaseName.substr(0, End));
Samuel Antao3b7e38b2016-10-27 18:14:55 +00004221 Suffixed += OffloadingPrefix;
Mehdi Aminic50b1a22016-10-07 21:27:26 +00004222 if (MultipleArchs && !BoundArch.empty()) {
Chad Rosier35767232013-04-30 22:01:21 +00004223 Suffixed += "-";
4224 Suffixed.append(BoundArch);
4225 }
Bob Wilson23a55f12014-12-21 07:00:00 +00004226 // When using both -save-temps and -emit-llvm, use a ".tmp.bc" suffix for
4227 // the unoptimized bitcode so that it does not get overwritten by the ".bc"
4228 // optimized bitcode output.
4229 if (!AtTopLevel && C.getArgs().hasArg(options::OPT_emit_llvm) &&
4230 JA.getType() == types::TY_LLVM_BC)
4231 Suffixed += ".tmp";
Daniel Dunbar7a178a42009-03-17 17:53:55 +00004232 Suffixed += '.';
4233 Suffixed += Suffix;
4234 NamedOutput = C.getArgs().MakeArgString(Suffixed.c_str());
4235 }
4236
Reid Kleckner68eb60b2015-02-02 22:41:48 +00004237 // Prepend object file path if -save-temps=obj
4238 if (!AtTopLevel && isSaveTempsObj() && C.getArgs().hasArg(options::OPT_o) &&
4239 JA.getType() != types::TY_PCH) {
4240 Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o);
4241 SmallString<128> TempPath(FinalOutput->getValue());
4242 llvm::sys::path::remove_filename(TempPath);
4243 StringRef OutputFileName = llvm::sys::path::filename(NamedOutput);
4244 llvm::sys::path::append(TempPath, OutputFileName);
4245 NamedOutput = C.getArgs().MakeArgString(TempPath.c_str());
4246 }
4247
Chad Rosier62135492012-07-09 17:31:28 +00004248 // If we're saving temps and the temp file conflicts with the input file,
Chad Rosier5b58af02012-04-20 20:05:08 +00004249 // then avoid overwriting input file.
Reid Kleckner68eb60b2015-02-02 22:41:48 +00004250 if (!AtTopLevel && isSaveTempsEnabled() && NamedOutput == BaseName) {
Chad Rosier5b58af02012-04-20 20:05:08 +00004251 bool SameFile = false;
4252 SmallString<256> Result;
4253 llvm::sys::fs::current_path(Result);
4254 llvm::sys::path::append(Result, BaseName);
4255 llvm::sys::fs::equivalent(BaseInput, Result.c_str(), SameFile);
4256 // Must share the same path to conflict.
4257 if (SameFile) {
4258 StringRef Name = llvm::sys::path::filename(BaseInput);
4259 std::pair<StringRef, StringRef> Split = Name.split('.');
Douglas Katzmana67e50c2015-06-26 15:47:46 +00004260 std::string TmpName = GetTemporaryPath(
4261 Split.first, types::getTypeTempSuffix(JA.getType(), IsCLMode()));
Malcolm Parsonsf76f6502016-11-02 10:39:27 +00004262 return C.addTempFile(C.getArgs().MakeArgString(TmpName));
Chad Rosier5b58af02012-04-20 20:05:08 +00004263 }
Chad Rosierf8412cd2011-07-15 21:54:29 +00004264 }
4265
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00004266 // As an annoying special case, PCH generation doesn't strip the pathname.
Nico Weber8ab92192016-03-02 23:29:29 +00004267 if (JA.getType() == types::TY_PCH && !IsCLMode()) {
Michael J. Spencere1696752010-12-18 00:19:12 +00004268 llvm::sys::path::remove_filename(BasePath);
4269 if (BasePath.empty())
Daniel Dunbare6c83192009-03-18 09:58:30 +00004270 BasePath = NamedOutput;
4271 else
Michael J. Spencere1696752010-12-18 00:19:12 +00004272 llvm::sys::path::append(BasePath, NamedOutput);
Chad Rosier633dcdc2013-01-24 19:14:47 +00004273 return C.addResultFile(C.getArgs().MakeArgString(BasePath.c_str()), &JA);
Daniel Dunbar7a178a42009-03-17 17:53:55 +00004274 } else {
Chad Rosier633dcdc2013-01-24 19:14:47 +00004275 return C.addResultFile(NamedOutput, &JA);
Daniel Dunbar7a178a42009-03-17 17:53:55 +00004276 }
4277}
4278
Mehdi Amini12011172016-10-06 05:11:48 +00004279std::string Driver::GetFilePath(StringRef Name, const ToolChain &TC) const {
Petr Hosek8f2499f2018-09-12 03:26:10 +00004280 // Seach for Name in a list of paths.
4281 auto SearchPaths = [&](const llvm::SmallVectorImpl<std::string> &P)
4282 -> llvm::Optional<std::string> {
4283 // Respect a limited subset of the '-Bprefix' functionality in GCC by
4284 // attempting to use this prefix when looking for file paths.
4285 for (const auto &Dir : P) {
4286 if (Dir.empty())
4287 continue;
4288 SmallString<128> P(Dir[0] == '=' ? SysRoot + Dir.substr(1) : Dir);
4289 llvm::sys::path::append(P, Name);
4290 if (llvm::sys::fs::exists(Twine(P)))
Simon Pilgrim4588fc82018-09-13 10:10:18 +00004291 return P.str().str();
Petr Hosek8f2499f2018-09-12 03:26:10 +00004292 }
4293 return None;
4294 };
4295
4296 if (auto P = SearchPaths(PrefixDirs))
4297 return *P;
Chandler Carruth84559242010-03-22 01:52:07 +00004298
Petr Hosek916a4672017-08-10 04:16:38 +00004299 SmallString<128> R(ResourceDir);
4300 llvm::sys::path::append(R, Name);
4301 if (llvm::sys::fs::exists(Twine(R)))
4302 return R.str();
4303
4304 SmallString<128> P(TC.getCompilerRTPath());
Rafael Espindola609a6642013-06-24 18:33:43 +00004305 llvm::sys::path::append(P, Name);
4306 if (llvm::sys::fs::exists(Twine(P)))
Peter Collingbournefa9771f2011-09-06 02:08:31 +00004307 return P.str();
4308
Petr Hosek8f2499f2018-09-12 03:26:10 +00004309 if (auto P = SearchPaths(TC.getLibraryPaths()))
4310 return *P;
4311
4312 if (auto P = SearchPaths(TC.getFilePaths()))
4313 return *P;
Daniel Dunbar68b01a02009-03-18 20:26:19 +00004314
Daniel Dunbar1ce81532009-09-09 22:33:00 +00004315 return Name;
Daniel Dunbar5e0f6af2009-03-13 00:51:18 +00004316}
4317
Douglas Katzmana67e50c2015-06-26 15:47:46 +00004318void Driver::generatePrefixedToolNames(
Mehdi Amini12011172016-10-06 05:11:48 +00004319 StringRef Tool, const ToolChain &TC,
Douglas Katzmana67e50c2015-06-26 15:47:46 +00004320 SmallVectorImpl<std::string> &Names) const {
Petr Hosekdd38d932018-05-29 22:35:39 +00004321 // FIXME: Needs a better variable than TargetTriple
4322 Names.emplace_back((TargetTriple + "-" + Tool).str());
Benjamin Kramer3204b152015-05-29 19:42:19 +00004323 Names.emplace_back(Tool);
Vasileios Kalintirisc744e122015-11-12 15:26:54 +00004324
4325 // Allow the discovery of tools prefixed with LLVM's default target triple.
Petr Hosekdd38d932018-05-29 22:35:39 +00004326 std::string DefaultTargetTriple = llvm::sys::getDefaultTargetTriple();
4327 if (DefaultTargetTriple != TargetTriple)
4328 Names.emplace_back((DefaultTargetTriple + "-" + Tool).str());
Saleem Abdulrasoolf0ba6ce2014-10-25 23:33:21 +00004329}
4330
Benjamin Kramer7111b912014-11-04 20:26:01 +00004331static bool ScanDirForExecutable(SmallString<128> &Dir,
4332 ArrayRef<std::string> Names) {
Saleem Abdulrasoolf0ba6ce2014-10-25 23:33:21 +00004333 for (const auto &Name : Names) {
4334 llvm::sys::path::append(Dir, Name);
4335 if (llvm::sys::fs::can_execute(Twine(Dir)))
4336 return true;
4337 llvm::sys::path::remove_filename(Dir);
4338 }
4339 return false;
4340}
4341
Mehdi Amini12011172016-10-06 05:11:48 +00004342std::string Driver::GetProgramPath(StringRef Name, const ToolChain &TC) const {
Saleem Abdulrasoolf0ba6ce2014-10-25 23:33:21 +00004343 SmallVector<std::string, 2> TargetSpecificExecutables;
4344 generatePrefixedToolNames(Name, TC, TargetSpecificExecutables);
4345
Chandler Carruth84559242010-03-22 01:52:07 +00004346 // Respect a limited subset of the '-Bprefix' functionality in GCC by
Logan Chiencd679fd2012-10-04 08:08:56 +00004347 // attempting to use this prefix when looking for program paths.
Saleem Abdulrasool23d99b12014-09-16 03:48:32 +00004348 for (const auto &PrefixDir : PrefixDirs) {
4349 if (llvm::sys::fs::is_directory(PrefixDir)) {
4350 SmallString<128> P(PrefixDir);
Saleem Abdulrasoolf0ba6ce2014-10-25 23:33:21 +00004351 if (ScanDirForExecutable(P, TargetSpecificExecutables))
Rafael Espindola8be5c052013-06-19 13:24:29 +00004352 return P.str();
Simon Atanasyana47ba292012-10-31 14:39:28 +00004353 } else {
Mehdi Amini12011172016-10-06 05:11:48 +00004354 SmallString<128> P((PrefixDir + Name).str());
Rafael Espindola609a6642013-06-24 18:33:43 +00004355 if (llvm::sys::fs::can_execute(Twine(P)))
Rafael Espindola8be5c052013-06-19 13:24:29 +00004356 return P.str();
Simon Atanasyan86bdab72012-10-31 12:01:53 +00004357 }
Chandler Carruth84559242010-03-22 01:52:07 +00004358 }
4359
Daniel Dunbar68b01a02009-03-18 20:26:19 +00004360 const ToolChain::path_list &List = TC.getProgramPaths();
Saleem Abdulrasool23d99b12014-09-16 03:48:32 +00004361 for (const auto &Path : List) {
4362 SmallString<128> P(Path);
Saleem Abdulrasoolf0ba6ce2014-10-25 23:33:21 +00004363 if (ScanDirForExecutable(P, TargetSpecificExecutables))
Rafael Espindola8be5c052013-06-19 13:24:29 +00004364 return P.str();
Daniel Dunbar68b01a02009-03-18 20:26:19 +00004365 }
4366
Daniel Dunbar76ce7412009-03-23 16:15:50 +00004367 // If all else failed, search the path.
Michael J. Spencerb011d482014-11-07 21:30:32 +00004368 for (const auto &TargetSpecificExecutable : TargetSpecificExecutables)
4369 if (llvm::ErrorOr<std::string> P =
4370 llvm::sys::findProgramByName(TargetSpecificExecutable))
Michael J. Spencer04162ea2014-11-04 01:30:55 +00004371 return *P;
Daniel Dunbar6f668772009-03-18 21:34:08 +00004372
Daniel Dunbar1ce81532009-09-09 22:33:00 +00004373 return Name;
Daniel Dunbar5e0f6af2009-03-13 00:51:18 +00004374}
4375
Mehdi Amini12011172016-10-06 05:11:48 +00004376std::string Driver::GetTemporaryPath(StringRef Prefix, StringRef Suffix) const {
Rafael Espindola37d229d2013-06-25 04:26:55 +00004377 SmallString<128> Path;
Rafael Espindolac0809172014-06-12 14:02:15 +00004378 std::error_code EC = llvm::sys::fs::createTemporaryFile(Prefix, Suffix, Path);
Rafael Espindola37d229d2013-06-25 04:26:55 +00004379 if (EC) {
4380 Diag(clang::diag::err_unable_to_make_temp) << EC.message();
Daniel Dunbare627c1c2009-03-18 19:34:39 +00004381 return "";
4382 }
4383
Rafael Espindola37d229d2013-06-25 04:26:55 +00004384 return Path.str();
Daniel Dunbare627c1c2009-03-18 19:34:39 +00004385}
4386
Nico Weber2ca4be92016-03-01 23:16:44 +00004387std::string Driver::GetClPchPath(Compilation &C, StringRef BaseName) const {
4388 SmallString<128> Output;
4389 if (Arg *FpArg = C.getArgs().getLastArg(options::OPT__SLASH_Fp)) {
4390 // FIXME: If anybody needs it, implement this obscure rule:
4391 // "If you specify a directory without a file name, the default file name
4392 // is VCx0.pch., where x is the major version of Visual C++ in use."
4393 Output = FpArg->getValue();
4394
4395 // "If you do not specify an extension as part of the path name, an
4396 // extension of .pch is assumed. "
4397 if (!llvm::sys::path::has_extension(Output))
4398 Output += ".pch";
4399 } else {
Mike Rice58df1af2018-09-11 17:10:44 +00004400 if (Arg *YcArg = C.getArgs().getLastArg(options::OPT__SLASH_Yc))
4401 Output = YcArg->getValue();
4402 if (Output.empty())
4403 Output = BaseName;
Nico Weber2ca4be92016-03-01 23:16:44 +00004404 llvm::sys::path::replace_extension(Output, ".pch");
4405 }
4406 return Output.str();
4407}
4408
Chandler Carruth2ad5de12012-01-25 11:01:57 +00004409const ToolChain &Driver::getToolChain(const ArgList &Args,
Artem Belevich959e0542015-07-10 19:47:55 +00004410 const llvm::Triple &Target) const {
Chandler Carruth2ad5de12012-01-25 11:01:57 +00004411
David Blaikie6ad71012017-01-13 18:53:43 +00004412 auto &TC = ToolChains[Target.str()];
Chandler Carruth2ad5de12012-01-25 11:01:57 +00004413 if (!TC) {
4414 switch (Target.getOS()) {
Reid Kleckner330fb172016-05-11 16:19:05 +00004415 case llvm::Triple::Haiku:
David Blaikie6ad71012017-01-13 18:53:43 +00004416 TC = llvm::make_unique<toolchains::Haiku>(*this, Target, Args);
Reid Kleckner330fb172016-05-11 16:19:05 +00004417 break;
Ed Schouten4dabea22017-06-25 08:29:09 +00004418 case llvm::Triple::Ananas:
4419 TC = llvm::make_unique<toolchains::Ananas>(*this, Target, Args);
4420 break;
Ed Schouten3c3e58c2015-03-26 11:13:44 +00004421 case llvm::Triple::CloudABI:
David Blaikie6ad71012017-01-13 18:53:43 +00004422 TC = llvm::make_unique<toolchains::CloudABI>(*this, Target, Args);
Ed Schouten3c3e58c2015-03-26 11:13:44 +00004423 break;
Chandler Carruth2ad5de12012-01-25 11:01:57 +00004424 case llvm::Triple::Darwin:
4425 case llvm::Triple::MacOSX:
4426 case llvm::Triple::IOS:
Tim Northover6f3ff222015-10-30 16:30:27 +00004427 case llvm::Triple::TvOS:
4428 case llvm::Triple::WatchOS:
David Blaikie6ad71012017-01-13 18:53:43 +00004429 TC = llvm::make_unique<toolchains::DarwinClang>(*this, Target, Args);
Chandler Carruth2ad5de12012-01-25 11:01:57 +00004430 break;
4431 case llvm::Triple::DragonFly:
David Blaikie6ad71012017-01-13 18:53:43 +00004432 TC = llvm::make_unique<toolchains::DragonFly>(*this, Target, Args);
Chandler Carruth2ad5de12012-01-25 11:01:57 +00004433 break;
4434 case llvm::Triple::OpenBSD:
David Blaikie6ad71012017-01-13 18:53:43 +00004435 TC = llvm::make_unique<toolchains::OpenBSD>(*this, Target, Args);
Chandler Carruth2ad5de12012-01-25 11:01:57 +00004436 break;
4437 case llvm::Triple::NetBSD:
David Blaikie6ad71012017-01-13 18:53:43 +00004438 TC = llvm::make_unique<toolchains::NetBSD>(*this, Target, Args);
Chandler Carruth2ad5de12012-01-25 11:01:57 +00004439 break;
4440 case llvm::Triple::FreeBSD:
David Blaikie6ad71012017-01-13 18:53:43 +00004441 TC = llvm::make_unique<toolchains::FreeBSD>(*this, Target, Args);
Chandler Carruth2ad5de12012-01-25 11:01:57 +00004442 break;
4443 case llvm::Triple::Minix:
David Blaikie6ad71012017-01-13 18:53:43 +00004444 TC = llvm::make_unique<toolchains::Minix>(*this, Target, Args);
Chandler Carruth2ad5de12012-01-25 11:01:57 +00004445 break;
4446 case llvm::Triple::Linux:
Andrey Turetskiy4798eb62016-06-16 10:36:09 +00004447 case llvm::Triple::ELFIAMCU:
Chandler Carruthcf705b22012-01-25 21:03:58 +00004448 if (Target.getArch() == llvm::Triple::hexagon)
David Blaikie6ad71012017-01-13 18:53:43 +00004449 TC = llvm::make_unique<toolchains::HexagonToolChain>(*this, Target,
4450 Args);
Vasileios Kalintirisc744e122015-11-12 15:26:54 +00004451 else if ((Target.getVendor() == llvm::Triple::MipsTechnologies) &&
4452 !Target.hasEnvironment())
David Blaikie6ad71012017-01-13 18:53:43 +00004453 TC = llvm::make_unique<toolchains::MipsLLVMToolChain>(*this, Target,
4454 Args);
Chandler Carruthcf705b22012-01-25 21:03:58 +00004455 else
David Blaikie6ad71012017-01-13 18:53:43 +00004456 TC = llvm::make_unique<toolchains::Linux>(*this, Target, Args);
Chandler Carruth2ad5de12012-01-25 11:01:57 +00004457 break;
Derek Schuff6ab52fa2015-03-30 20:31:33 +00004458 case llvm::Triple::NaCl:
David Blaikie6ad71012017-01-13 18:53:43 +00004459 TC = llvm::make_unique<toolchains::NaClToolChain>(*this, Target, Args);
Derek Schuff6ab52fa2015-03-30 20:31:33 +00004460 break;
Petr Hosek62e1d232016-10-06 06:08:09 +00004461 case llvm::Triple::Fuchsia:
David Blaikie6ad71012017-01-13 18:53:43 +00004462 TC = llvm::make_unique<toolchains::Fuchsia>(*this, Target, Args);
Petr Hosek62e1d232016-10-06 06:08:09 +00004463 break;
David Chisnallf571cde2012-02-15 13:39:01 +00004464 case llvm::Triple::Solaris:
David Blaikie6ad71012017-01-13 18:53:43 +00004465 TC = llvm::make_unique<toolchains::Solaris>(*this, Target, Args);
David Chisnallf571cde2012-02-15 13:39:01 +00004466 break;
Tom Stellard8fa33092015-07-18 01:49:05 +00004467 case llvm::Triple::AMDHSA:
David Blaikie6ad71012017-01-13 18:53:43 +00004468 TC = llvm::make_unique<toolchains::AMDGPUToolChain>(*this, Target, Args);
Tom Stellard8fa33092015-07-18 01:49:05 +00004469 break;
Chandler Carruth2ad5de12012-01-25 11:01:57 +00004470 case llvm::Triple::Win32:
Saleem Abdulrasool377066a2014-03-27 22:50:18 +00004471 switch (Target.getEnvironment()) {
4472 default:
4473 if (Target.isOSBinFormatELF())
David Blaikie6ad71012017-01-13 18:53:43 +00004474 TC = llvm::make_unique<toolchains::Generic_ELF>(*this, Target, Args);
Saleem Abdulrasool377066a2014-03-27 22:50:18 +00004475 else if (Target.isOSBinFormatMachO())
David Blaikie6ad71012017-01-13 18:53:43 +00004476 TC = llvm::make_unique<toolchains::MachO>(*this, Target, Args);
Saleem Abdulrasool377066a2014-03-27 22:50:18 +00004477 else
David Blaikie6ad71012017-01-13 18:53:43 +00004478 TC = llvm::make_unique<toolchains::Generic_GCC>(*this, Target, Args);
Saleem Abdulrasool377066a2014-03-27 22:50:18 +00004479 break;
4480 case llvm::Triple::GNU:
David Blaikie6ad71012017-01-13 18:53:43 +00004481 TC = llvm::make_unique<toolchains::MinGW>(*this, Target, Args);
Saleem Abdulrasool377066a2014-03-27 22:50:18 +00004482 break;
Saleem Abdulrasool543a78b2014-10-24 03:13:37 +00004483 case llvm::Triple::Itanium:
David Blaikie6ad71012017-01-13 18:53:43 +00004484 TC = llvm::make_unique<toolchains::CrossWindowsToolChain>(*this, Target,
4485 Args);
Saleem Abdulrasool543a78b2014-10-24 03:13:37 +00004486 break;
Saleem Abdulrasool377066a2014-03-27 22:50:18 +00004487 case llvm::Triple::MSVC:
4488 case llvm::Triple::UnknownEnvironment:
Dave Leef96bedf2017-11-06 21:18:05 +00004489 if (Args.getLastArgValue(options::OPT_fuse_ld_EQ)
4490 .startswith_lower("bfd"))
4491 TC = llvm::make_unique<toolchains::CrossWindowsToolChain>(
4492 *this, Target, Args);
4493 else
4494 TC =
4495 llvm::make_unique<toolchains::MSVCToolChain>(*this, Target, Args);
Saleem Abdulrasool377066a2014-03-27 22:50:18 +00004496 break;
4497 }
Chandler Carruth2ad5de12012-01-25 11:01:57 +00004498 break;
Filipe Cabecinhasc888e192015-10-14 12:25:43 +00004499 case llvm::Triple::PS4:
David Blaikie6ad71012017-01-13 18:53:43 +00004500 TC = llvm::make_unique<toolchains::PS4CPU>(*this, Target, Args);
Filipe Cabecinhasc888e192015-10-14 12:25:43 +00004501 break;
David L Kreitzerd397ea42016-10-14 20:44:33 +00004502 case llvm::Triple::Contiki:
David Blaikie6ad71012017-01-13 18:53:43 +00004503 TC = llvm::make_unique<toolchains::Contiki>(*this, Target, Args);
David L Kreitzerd397ea42016-10-14 20:44:33 +00004504 break;
Chandler Carruth2ad5de12012-01-25 11:01:57 +00004505 default:
Douglas Katzman9f5e70e2015-05-26 18:01:33 +00004506 // Of these targets, Hexagon is the only one that might have
4507 // an OS of Linux, in which case it got handled above already.
Douglas Katzman15a63ed2015-08-12 18:36:12 +00004508 switch (Target.getArch()) {
4509 case llvm::Triple::tce:
David Blaikie6ad71012017-01-13 18:53:43 +00004510 TC = llvm::make_unique<toolchains::TCEToolChain>(*this, Target, Args);
Douglas Katzman15a63ed2015-08-12 18:36:12 +00004511 break;
Pekka Jaaskelainen67354482016-11-16 15:22:31 +00004512 case llvm::Triple::tcele:
David Blaikie6ad71012017-01-13 18:53:43 +00004513 TC = llvm::make_unique<toolchains::TCELEToolChain>(*this, Target, Args);
Pekka Jaaskelainen67354482016-11-16 15:22:31 +00004514 break;
Douglas Katzman15a63ed2015-08-12 18:36:12 +00004515 case llvm::Triple::hexagon:
David Blaikie6ad71012017-01-13 18:53:43 +00004516 TC = llvm::make_unique<toolchains::HexagonToolChain>(*this, Target,
4517 Args);
Douglas Katzman15a63ed2015-08-12 18:36:12 +00004518 break;
Jacques Pienaard964cc22016-03-28 21:02:54 +00004519 case llvm::Triple::lanai:
David Blaikie6ad71012017-01-13 18:53:43 +00004520 TC = llvm::make_unique<toolchains::LanaiToolChain>(*this, Target, Args);
Jacques Pienaard964cc22016-03-28 21:02:54 +00004521 break;
Douglas Katzman15a63ed2015-08-12 18:36:12 +00004522 case llvm::Triple::xcore:
David Blaikie6ad71012017-01-13 18:53:43 +00004523 TC = llvm::make_unique<toolchains::XCoreToolChain>(*this, Target, Args);
Douglas Katzman15a63ed2015-08-12 18:36:12 +00004524 break;
Dan Gohmanc2853072015-09-03 22:51:53 +00004525 case llvm::Triple::wasm32:
4526 case llvm::Triple::wasm64:
David Blaikie6ad71012017-01-13 18:53:43 +00004527 TC = llvm::make_unique<toolchains::WebAssembly>(*this, Target, Args);
Dan Gohmanc2853072015-09-03 22:51:53 +00004528 break;
Dylan McKay924fa3a2017-01-05 05:20:27 +00004529 case llvm::Triple::avr:
David Blaikie6ad71012017-01-13 18:53:43 +00004530 TC = llvm::make_unique<toolchains::AVRToolChain>(*this, Target, Args);
Dylan McKay924fa3a2017-01-05 05:20:27 +00004531 break;
David Bolvanskyf4be2532018-07-31 14:21:46 +00004532 case llvm::Triple::riscv32:
4533 case llvm::Triple::riscv64:
4534 TC = llvm::make_unique<toolchains::RISCVToolChain>(*this, Target, Args);
4535 break;
Douglas Katzman15a63ed2015-08-12 18:36:12 +00004536 default:
Douglas Katzmand6e597c2015-09-17 19:56:40 +00004537 if (Target.getVendor() == llvm::Triple::Myriad)
David Blaikie6ad71012017-01-13 18:53:43 +00004538 TC = llvm::make_unique<toolchains::MyriadToolChain>(*this, Target,
4539 Args);
Jonathan Roelofs901c7762017-05-25 15:42:13 +00004540 else if (toolchains::BareMetal::handlesTarget(Target))
4541 TC = llvm::make_unique<toolchains::BareMetal>(*this, Target, Args);
Douglas Katzmand6e597c2015-09-17 19:56:40 +00004542 else if (Target.isOSBinFormatELF())
David Blaikie6ad71012017-01-13 18:53:43 +00004543 TC = llvm::make_unique<toolchains::Generic_ELF>(*this, Target, Args);
Douglas Katzman15a63ed2015-08-12 18:36:12 +00004544 else if (Target.isOSBinFormatMachO())
David Blaikie6ad71012017-01-13 18:53:43 +00004545 TC = llvm::make_unique<toolchains::MachO>(*this, Target, Args);
Douglas Katzman15a63ed2015-08-12 18:36:12 +00004546 else
David Blaikie6ad71012017-01-13 18:53:43 +00004547 TC = llvm::make_unique<toolchains::Generic_GCC>(*this, Target, Args);
Douglas Katzman15a63ed2015-08-12 18:36:12 +00004548 }
Chandler Carruth2ad5de12012-01-25 11:01:57 +00004549 }
4550 }
Justin Lebar66c4fd72016-11-18 00:41:22 +00004551
4552 // Intentionally omitted from the switch above: llvm::Triple::CUDA. CUDA
4553 // compiles always need two toolchains, the CUDA toolchain and the host
4554 // toolchain. So the only valid way to create a CUDA toolchain is via
4555 // CreateOffloadingDeviceToolChains.
4556
Chandler Carruth2ad5de12012-01-25 11:01:57 +00004557 return *TC;
Daniel Dunbar4dff6a42009-03-10 23:41:59 +00004558}
Daniel Dunbar8fa879d2009-03-24 18:57:02 +00004559
Rafael Espindola2f69d402013-03-18 15:33:26 +00004560bool Driver::ShouldUseClangCompiler(const JobAction &JA) const {
Douglas Katzman00249092015-06-12 15:45:21 +00004561 // Say "no" if there is not exactly one input of a type clang understands.
Nico Weber5a459f82016-02-23 19:30:43 +00004562 if (JA.size() != 1 ||
4563 !types::isAcceptedByClang((*JA.input_begin())->getType()))
Nick Lewycky5cc9ebb2012-11-15 05:36:36 +00004564 return false;
4565
Douglas Katzman00249092015-06-12 15:45:21 +00004566 // And say "no" if this is not a kind of action clang understands.
Nick Lewycky5cc9ebb2012-11-15 05:36:36 +00004567 if (!isa<PreprocessJobAction>(JA) && !isa<PrecompileJobAction>(JA) &&
Bob Wilson23a55f12014-12-21 07:00:00 +00004568 !isa<CompileJobAction>(JA) && !isa<BackendJobAction>(JA))
Nick Lewycky5cc9ebb2012-11-15 05:36:36 +00004569 return false;
4570
4571 return true;
4572}
4573
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00004574/// GetReleaseVersion - Parse (([0-9]+)(.([0-9]+)(.([0-9]+)?))?)? and return the
4575/// grouped values as integers. Numbers which are not provided are set to 0.
Daniel Dunbarc7fd57a2009-03-26 15:58:36 +00004576///
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00004577/// \return True if the entire string was parsed (9.2), or all groups were
4578/// parsed (10.3.5extrastuff).
Mehdi Amini12011172016-10-06 05:11:48 +00004579bool Driver::GetReleaseVersion(StringRef Str, unsigned &Major, unsigned &Minor,
4580 unsigned &Micro, bool &HadExtra) {
Daniel Dunbarc7fd57a2009-03-26 15:58:36 +00004581 HadExtra = false;
4582
4583 Major = Minor = Micro = 0;
Mehdi Amini12011172016-10-06 05:11:48 +00004584 if (Str.empty())
Bob Wilson433cb312015-04-07 01:03:35 +00004585 return false;
Daniel Dunbarc7fd57a2009-03-26 15:58:36 +00004586
Mehdi Amini12011172016-10-06 05:11:48 +00004587 if (Str.consumeInteger(10, Major))
4588 return false;
4589 if (Str.empty())
Daniel Dunbarc7fd57a2009-03-26 15:58:36 +00004590 return true;
Mehdi Amini12011172016-10-06 05:11:48 +00004591 if (Str[0] != '.')
Daniel Dunbarc7fd57a2009-03-26 15:58:36 +00004592 return false;
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00004593
Mehdi Amini12011172016-10-06 05:11:48 +00004594 Str = Str.drop_front(1);
Daniel Dunbarc7fd57a2009-03-26 15:58:36 +00004595
Mehdi Amini12011172016-10-06 05:11:48 +00004596 if (Str.consumeInteger(10, Minor))
Daniel Dunbarc7fd57a2009-03-26 15:58:36 +00004597 return false;
Mehdi Amini12011172016-10-06 05:11:48 +00004598 if (Str.empty())
4599 return true;
4600 if (Str[0] != '.')
4601 return false;
4602 Str = Str.drop_front(1);
4603
4604 if (Str.consumeInteger(10, Micro))
4605 return false;
4606 if (!Str.empty())
4607 HadExtra = true;
Daniel Dunbarc7fd57a2009-03-26 15:58:36 +00004608 return true;
4609}
Hans Wennborg6ddc6902013-07-27 00:23:45 +00004610
Bruno Cardoso Lopes8ed5cac2016-03-31 02:45:46 +00004611/// Parse digits from a string \p Str and fulfill \p Digits with
4612/// the parsed numbers. This method assumes that the max number of
4613/// digits to look for is equal to Digits.size().
4614///
4615/// \return True if the entire string was parsed and there are
4616/// no extra characters remaining at the end.
Mehdi Amini12011172016-10-06 05:11:48 +00004617bool Driver::GetReleaseVersion(StringRef Str,
Bruno Cardoso Lopes8ed5cac2016-03-31 02:45:46 +00004618 MutableArrayRef<unsigned> Digits) {
Mehdi Amini12011172016-10-06 05:11:48 +00004619 if (Str.empty())
Bruno Cardoso Lopes8ed5cac2016-03-31 02:45:46 +00004620 return false;
4621
Bruno Cardoso Lopes8ed5cac2016-03-31 02:45:46 +00004622 unsigned CurDigit = 0;
4623 while (CurDigit < Digits.size()) {
Mehdi Amini12011172016-10-06 05:11:48 +00004624 unsigned Digit;
4625 if (Str.consumeInteger(10, Digit))
Bruno Cardoso Lopes8ed5cac2016-03-31 02:45:46 +00004626 return false;
Mehdi Amini12011172016-10-06 05:11:48 +00004627 Digits[CurDigit] = Digit;
4628 if (Str.empty())
4629 return true;
4630 if (Str[0] != '.')
4631 return false;
4632 Str = Str.drop_front(1);
Bruno Cardoso Lopes8ed5cac2016-03-31 02:45:46 +00004633 CurDigit++;
4634 }
4635
4636 // More digits than requested, bail out...
4637 return false;
4638}
4639
Hans Wennborg6ddc6902013-07-27 00:23:45 +00004640std::pair<unsigned, unsigned> Driver::getIncludeExcludeOptionFlagMasks() const {
4641 unsigned IncludedFlagsBitmask = 0;
Rafael Espindolacc707bc2013-09-25 15:54:41 +00004642 unsigned ExcludedFlagsBitmask = options::NoDriverOption;
Hans Wennborg6ddc6902013-07-27 00:23:45 +00004643
4644 if (Mode == CLMode) {
Hans Wennborg19076102013-07-31 20:51:53 +00004645 // Include CL and Core options.
4646 IncludedFlagsBitmask |= options::CLOption;
4647 IncludedFlagsBitmask |= options::CoreOption;
Hans Wennborg6ddc6902013-07-27 00:23:45 +00004648 } else {
4649 ExcludedFlagsBitmask |= options::CLOption;
4650 }
4651
4652 return std::make_pair(IncludedFlagsBitmask, ExcludedFlagsBitmask);
4653}
Benjamin Kramerab88f622014-03-25 18:02:07 +00004654
Douglas Katzmanf08fadf2015-06-04 14:40:44 +00004655bool clang::driver::isOptimizationLevelFast(const ArgList &Args) {
Benjamin Kramerab88f622014-03-25 18:02:07 +00004656 return Args.hasFlag(options::OPT_Ofast, options::OPT_O_Group, false);
4657}