blob: 238315e8b93fd9177d6bb232665bcff901da0e8d [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//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Daniel Dunbar544ecd12009-03-02 19:59:07 +00006//
7//===----------------------------------------------------------------------===//
8
Daniel Dunbar544ecd12009-03-02 19:59:07 +00009#include "clang/Driver/Driver.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000010#include "InputInfo.h"
David L. Jonesf561aba2017-03-08 01:02:16 +000011#include "ToolChains/AMDGPU.h"
12#include "ToolChains/AVR.h"
Ed Schouten4dabea22017-06-25 08:29:09 +000013#include "ToolChains/Ananas.h"
Yaxun Liuf6144222018-05-30 00:53:50 +000014#include "ToolChains/BareMetal.h"
David L. Jonesf561aba2017-03-08 01:02:16 +000015#include "ToolChains/Clang.h"
16#include "ToolChains/CloudABI.h"
17#include "ToolChains/Contiki.h"
18#include "ToolChains/CrossWindows.h"
19#include "ToolChains/Cuda.h"
20#include "ToolChains/Darwin.h"
21#include "ToolChains/DragonFly.h"
22#include "ToolChains/FreeBSD.h"
23#include "ToolChains/Fuchsia.h"
24#include "ToolChains/Gnu.h"
Yaxun Liuf6144222018-05-30 00:53:50 +000025#include "ToolChains/HIP.h"
David L. Jonesf561aba2017-03-08 01:02:16 +000026#include "ToolChains/Haiku.h"
27#include "ToolChains/Hexagon.h"
Kristina Brooks77a4adc2018-11-29 03:49:14 +000028#include "ToolChains/Hurd.h"
David L. Jonesf561aba2017-03-08 01:02:16 +000029#include "ToolChains/Lanai.h"
30#include "ToolChains/Linux.h"
Anton Korobeynikov93165d62019-01-15 19:44:05 +000031#include "ToolChains/MSP430.h"
Yaxun Liuf6144222018-05-30 00:53:50 +000032#include "ToolChains/MSVC.h"
David L. Jonesf561aba2017-03-08 01:02:16 +000033#include "ToolChains/MinGW.h"
34#include "ToolChains/Minix.h"
Konstantin Zhuravlyove37b32c2017-03-08 22:36:04 +000035#include "ToolChains/MipsLinux.h"
David L. Jonesf561aba2017-03-08 01:02:16 +000036#include "ToolChains/Myriad.h"
37#include "ToolChains/NaCl.h"
38#include "ToolChains/NetBSD.h"
39#include "ToolChains/OpenBSD.h"
40#include "ToolChains/PS4CPU.h"
Qiu Chaofan19828e32019-04-23 05:50:24 +000041#include "ToolChains/PPCLinux.h"
Erik Pilkington46420b62018-09-27 20:36:28 +000042#include "ToolChains/RISCVToolchain.h"
David L. Jonesf561aba2017-03-08 01:02:16 +000043#include "ToolChains/Solaris.h"
44#include "ToolChains/TCE.h"
45#include "ToolChains/WebAssembly.h"
46#include "ToolChains/XCore.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000047#include "clang/Basic/Version.h"
Alp Toker1d257e12014-06-04 03:28:55 +000048#include "clang/Config/config.h"
Daniel Dunbar1688f1a2009-03-12 07:58:46 +000049#include "clang/Driver/Action.h"
Daniel Dunbarb2cd66b2009-03-04 20:49:20 +000050#include "clang/Driver/Compilation.h"
Daniel Dunbarc0b3e952009-03-12 08:55:43 +000051#include "clang/Driver/DriverDiagnostic.h"
Daniel Dunbare75d8342009-03-16 06:56:51 +000052#include "clang/Driver/Job.h"
Daniel Dunbarb2cd66b2009-03-04 20:49:20 +000053#include "clang/Driver/Options.h"
Peter Collingbournea4ccff32015-02-20 20:30:56 +000054#include "clang/Driver/SanitizerArgs.h"
Daniel Dunbare75d8342009-03-16 06:56:51 +000055#include "clang/Driver/Tool.h"
56#include "clang/Driver/ToolChain.h"
Chris Lattnerce6c42f2011-03-23 04:04:01 +000057#include "llvm/ADT/ArrayRef.h"
Hans Wennborg6ddc6902013-07-27 00:23:45 +000058#include "llvm/ADT/STLExtras.h"
Justin Lebar62907612016-07-06 21:21:39 +000059#include "llvm/ADT/SmallSet.h"
Hans Wennborg23d26a32014-06-18 17:21:50 +000060#include "llvm/ADT/StringExtras.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000061#include "llvm/ADT/StringSet.h"
Hans Wennborg70850d82013-07-18 20:29:38 +000062#include "llvm/ADT/StringSwitch.h"
Nico Weberd637c052018-04-30 13:52:15 +000063#include "llvm/Config/llvm-config.h"
Reid Kleckner898229a2013-06-14 17:17:23 +000064#include "llvm/Option/Arg.h"
65#include "llvm/Option/ArgList.h"
Chandler Carruth5553d0d2014-01-07 11:51:46 +000066#include "llvm/Option/OptSpecifier.h"
Reid Kleckner898229a2013-06-14 17:17:23 +000067#include "llvm/Option/OptTable.h"
68#include "llvm/Option/Option.h"
Serge Pavlov208ac652018-01-01 13:27:01 +000069#include "llvm/Support/CommandLine.h"
David Blaikie79000202011-09-23 05:57:42 +000070#include "llvm/Support/ErrorHandling.h"
Michael J. Spencerf28df4c2010-12-17 21:22:22 +000071#include "llvm/Support/FileSystem.h"
Fangrui Songd0028232018-10-10 00:15:33 +000072#include "llvm/Support/FormatVariadic.h"
Michael J. Spencer8aaf4992010-11-29 18:12:39 +000073#include "llvm/Support/Path.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000074#include "llvm/Support/PrettyStackTrace.h"
Hans Wennborg23d26a32014-06-18 17:21:50 +000075#include "llvm/Support/Process.h"
Michael J. Spencer8aaf4992010-11-29 18:12:39 +000076#include "llvm/Support/Program.h"
Yaxun Liuf6144222018-05-30 00:53:50 +000077#include "llvm/Support/StringSaver.h"
Dimitry Andric81c40422017-06-06 21:54:21 +000078#include "llvm/Support/TargetRegistry.h"
Jonas Devliegherefc514902018-10-10 13:27:25 +000079#include "llvm/Support/VirtualFileSystem.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000080#include "llvm/Support/raw_ostream.h"
Dylan Noblesmith4f4e7452012-02-02 00:40:14 +000081#include <map>
Ahmed Charlesdfca6f92014-03-09 11:36:40 +000082#include <memory>
Benjamin Kramercfeacf52016-05-27 14:27:13 +000083#include <utility>
Bruno Cardoso Lopes02681c42016-11-17 21:41:22 +000084#if LLVM_ON_UNIX
85#include <unistd.h> // getpid
Nick Desaulniers9d0df312018-10-15 17:39:00 +000086#include <sysexits.h> // EX_IOERR
Bruno Cardoso Lopes02681c42016-11-17 21:41:22 +000087#endif
Dylan Noblesmith86780e92012-02-01 14:25:28 +000088
Daniel Dunbarb2cd66b2009-03-04 20:49:20 +000089using namespace clang::driver;
Chris Lattnerada1c912009-03-26 05:56:24 +000090using namespace clang;
Reid Kleckner898229a2013-06-14 17:17:23 +000091using namespace llvm::opt;
Daniel Dunbarb2cd66b2009-03-04 20:49:20 +000092
Nico Weber0abcafd2019-01-31 22:15:32 +000093// static
94std::string Driver::GetResourcesPath(StringRef BinaryPath,
95 StringRef CustomResourceDir) {
96 // Since the resource directory is embedded in the module hash, it's important
97 // that all places that need it call this function, so that they get the
98 // exact same string ("a/../b/" and "b/" get different hashes, for example).
99
100 // Dir is bin/ or lib/, depending on where BinaryPath is.
101 std::string Dir = llvm::sys::path::parent_path(BinaryPath);
102
103 SmallString<128> P(Dir);
104 if (CustomResourceDir != "") {
105 llvm::sys::path::append(P, CustomResourceDir);
106 } else {
107 // On Windows, libclang.dll is in bin/.
108 // On non-Windows, libclang.so/.dylib is in lib/.
109 // With a static-library build of libclang, LibClangPath will contain the
110 // path of the embedding binary, which for LLVM binaries will be in bin/.
111 // ../lib gets us to lib/ in both cases.
112 P = llvm::sys::path::parent_path(Dir);
113 llvm::sys::path::append(P, Twine("lib") + CLANG_LIBDIR_SUFFIX, "clang",
114 CLANG_VERSION_STRING);
115 }
116
117 return P.str();
118}
119
Petr Hosekdd38d932018-05-29 22:35:39 +0000120Driver::Driver(StringRef ClangExecutable, StringRef TargetTriple,
Benjamin Kramerd45b2052015-10-07 15:48:01 +0000121 DiagnosticsEngine &Diags,
Jonas Devliegherefc514902018-10-10 13:27:25 +0000122 IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS)
Benjamin Kramercfeacf52016-05-27 14:27:13 +0000123 : Opts(createDriverOptTable()), Diags(Diags), VFS(std::move(VFS)),
124 Mode(GCCMode), SaveTemps(SaveTempsNone), BitcodeEmbed(EmbedNone),
125 LTOMode(LTOK_None), ClangExecutable(ClangExecutable),
Alex Lorenz045c5142018-04-07 00:03:27 +0000126 SysRoot(DEFAULT_SYSROOT), DriverTitle("clang LLVM compiler"),
127 CCPrintOptionsFilename(nullptr), CCPrintHeadersFilename(nullptr),
128 CCLogDiagnosticsFilename(nullptr), CCCPrintBindings(false),
129 CCPrintOptions(false), CCPrintHeaders(false), CCLogDiagnostics(false),
Petr Hosekdd38d932018-05-29 22:35:39 +0000130 CCGenDiagnostics(false), TargetTriple(TargetTriple),
Alex Lorenz045c5142018-04-07 00:03:27 +0000131 CCCGenericGCCName(""), Saver(Alloc), CheckInputsExist(true),
Erich Keane0a6b5b62018-12-04 14:34:09 +0000132 GenReproducer(false), SuppressMissingInputWarning(false) {
Daniel Dunbar3f3e2cd2010-01-20 02:35:16 +0000133
Benjamin Kramerd45b2052015-10-07 15:48:01 +0000134 // Provide a sane fallback if no VFS is specified.
135 if (!this->VFS)
Jonas Devliegherefc514902018-10-10 13:27:25 +0000136 this->VFS = llvm::vfs::getRealFileSystem();
Benjamin Kramerd45b2052015-10-07 15:48:01 +0000137
Sumanth Gundapaneni3a1592942015-03-03 20:43:12 +0000138 Name = llvm::sys::path::filename(ClangExecutable);
Douglas Katzmana67e50c2015-06-26 15:47:46 +0000139 Dir = llvm::sys::path::parent_path(ClangExecutable);
Benjamin Kramerf420dda2015-10-13 15:19:32 +0000140 InstalledDir = Dir; // Provide a sensible default installed dir.
Bob Wilsona20a1da2013-03-23 05:17:59 +0000141
Serge Pavlov208ac652018-01-01 13:27:01 +0000142#if defined(CLANG_CONFIG_FILE_SYSTEM_DIR)
143 SystemConfigDir = CLANG_CONFIG_FILE_SYSTEM_DIR;
144#endif
145#if defined(CLANG_CONFIG_FILE_USER_DIR)
146 UserConfigDir = CLANG_CONFIG_FILE_USER_DIR;
147#endif
148
Bob Wilsona20a1da2013-03-23 05:17:59 +0000149 // Compute the path to the resource directory.
Nico Weber0abcafd2019-01-31 22:15:32 +0000150 ResourceDir = GetResourcesPath(ClangExecutable, CLANG_RESOURCE_DIR);
Daniel Dunbar544ecd12009-03-02 19:59:07 +0000151}
152
Zachary Turneraff19c32016-08-12 17:47:52 +0000153void Driver::ParseDriverMode(StringRef ProgramName,
154 ArrayRef<const char *> Args) {
Martin Storsjo1fab23d2018-04-25 21:23:59 +0000155 if (ClangNameParts.isEmpty())
156 ClangNameParts = ToolChain::getTargetAndModeFromProgramName(ProgramName);
Serge Pavlov4e769842017-08-29 05:22:26 +0000157 setDriverModeFromOption(ClangNameParts.DriverMode);
Hans Wennborg70850d82013-07-18 20:29:38 +0000158
Douglas Katzman6bbffc42015-06-25 18:51:37 +0000159 for (const char *ArgPtr : Args) {
Erich Keane258f0592018-02-07 00:19:58 +0000160 // Ignore nullptrs, they are the response file's EOL markers.
Douglas Katzman6bbffc42015-06-25 18:51:37 +0000161 if (ArgPtr == nullptr)
Reid Kleckneraf5fd6a2014-08-22 19:29:30 +0000162 continue;
Douglas Katzman6bbffc42015-06-25 18:51:37 +0000163 const StringRef Arg = ArgPtr;
Zachary Turneraff19c32016-08-12 17:47:52 +0000164 setDriverModeFromOption(Arg);
Hans Wennborg70850d82013-07-18 20:29:38 +0000165 }
166}
167
Zachary Turneraff19c32016-08-12 17:47:52 +0000168void Driver::setDriverModeFromOption(StringRef Opt) {
169 const std::string OptName =
170 getOpts().getOption(options::OPT_driver_mode).getPrefixedName();
171 if (!Opt.startswith(OptName))
172 return;
173 StringRef Value = Opt.drop_front(OptName.size());
174
Erich Keane2908a042018-02-12 17:47:01 +0000175 if (auto M = llvm::StringSwitch<llvm::Optional<DriverMode>>(Value)
176 .Case("gcc", GCCMode)
177 .Case("g++", GXXMode)
178 .Case("cpp", CPPMode)
179 .Case("cl", CLMode)
180 .Default(None))
181 Mode = *M;
Zachary Turneraff19c32016-08-12 17:47:52 +0000182 else
183 Diag(diag::err_drv_unsupported_option_argument) << OptName << Value;
184}
185
Benjamin Kramer43c0f482017-06-30 13:21:27 +0000186InputArgList Driver::ParseArgStrings(ArrayRef<const char *> ArgStrings,
Hans Wennborg797004d2018-11-08 11:27:04 +0000187 bool IsClCompatMode,
Benjamin Kramer43c0f482017-06-30 13:21:27 +0000188 bool &ContainsError) {
Daniel Dunbar2608c542009-03-18 01:38:48 +0000189 llvm::PrettyStackTraceString CrashInfo("Command line argument parsing");
Benjamin Kramer43c0f482017-06-30 13:21:27 +0000190 ContainsError = false;
Hans Wennborg6ddc6902013-07-27 00:23:45 +0000191
192 unsigned IncludedFlagsBitmask;
193 unsigned ExcludedFlagsBitmask;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +0000194 std::tie(IncludedFlagsBitmask, ExcludedFlagsBitmask) =
Hans Wennborg797004d2018-11-08 11:27:04 +0000195 getIncludeExcludeOptionFlagMasks(IsClCompatMode);
Hans Wennborg6ddc6902013-07-27 00:23:45 +0000196
Daniel Dunbar52ed5fe2009-11-19 06:35:06 +0000197 unsigned MissingArgIndex, MissingArgCount;
David Blaikie69a1d8c2015-06-22 22:07:27 +0000198 InputArgList Args =
David Blaikie6d492ad2015-06-21 06:32:36 +0000199 getOpts().ParseArgs(ArgStrings, MissingArgIndex, MissingArgCount,
200 IncludedFlagsBitmask, ExcludedFlagsBitmask);
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +0000201
Daniel Dunbar52ed5fe2009-11-19 06:35:06 +0000202 // Check for missing argument error.
Benjamin Kramer43c0f482017-06-30 13:21:27 +0000203 if (MissingArgCount) {
204 Diag(diag::err_drv_missing_argument)
David Blaikie69a1d8c2015-06-22 22:07:27 +0000205 << Args.getArgString(MissingArgIndex) << MissingArgCount;
Benjamin Kramer43c0f482017-06-30 13:21:27 +0000206 ContainsError |=
207 Diags.getDiagnosticLevel(diag::err_drv_missing_argument,
208 SourceLocation()) > DiagnosticsEngine::Warning;
209 }
Daniel Dunbar65229332009-03-13 11:38:42 +0000210
Daniel Dunbar52ed5fe2009-11-19 06:35:06 +0000211 // Check for unsupported options.
David Blaikie69a1d8c2015-06-22 22:07:27 +0000212 for (const Arg *A : Args) {
Michael J. Spencer66e2b202012-10-19 22:37:06 +0000213 if (A->getOption().hasFlag(options::Unsupported)) {
Brian Gesiak24910762018-01-06 00:25:40 +0000214 unsigned DiagID;
215 auto ArgString = A->getAsString(Args);
216 std::string Nearest;
217 if (getOpts().findNearest(
218 ArgString, Nearest, IncludedFlagsBitmask,
219 ExcludedFlagsBitmask | options::Unsupported) > 1) {
220 DiagID = diag::err_drv_unsupported_opt;
221 Diag(DiagID) << ArgString;
222 } else {
223 DiagID = diag::err_drv_unsupported_opt_with_suggestion;
224 Diag(DiagID) << ArgString << Nearest;
225 }
226 ContainsError |= Diags.getDiagnosticLevel(DiagID, SourceLocation()) >
Benjamin Kramer43c0f482017-06-30 13:21:27 +0000227 DiagnosticsEngine::Warning;
Daniel Dunbard8500f32009-03-22 23:26:43 +0000228 continue;
229 }
Chad Rosierce975d92012-02-22 17:55:22 +0000230
231 // Warn about -mcpu= without an argument.
Douglas Katzmana67e50c2015-06-26 15:47:46 +0000232 if (A->getOption().matches(options::OPT_mcpu_EQ) && A->containsValue("")) {
Benjamin Kramer43c0f482017-06-30 13:21:27 +0000233 Diag(diag::warn_drv_empty_joined_argument) << A->getAsString(Args);
234 ContainsError |= Diags.getDiagnosticLevel(
235 diag::warn_drv_empty_joined_argument,
236 SourceLocation()) > DiagnosticsEngine::Warning;
Chad Rosierce975d92012-02-22 17:55:22 +0000237 }
Daniel Dunbard02cb1d2009-03-05 06:38:47 +0000238 }
239
Benjamin Kramer43c0f482017-06-30 13:21:27 +0000240 for (const Arg *A : Args.filtered(options::OPT_UNKNOWN)) {
Brian Gesiak24910762018-01-06 00:25:40 +0000241 unsigned DiagID;
242 auto ArgString = A->getAsString(Args);
243 std::string Nearest;
244 if (getOpts().findNearest(
245 ArgString, Nearest, IncludedFlagsBitmask, ExcludedFlagsBitmask) > 1) {
246 DiagID = IsCLMode() ? diag::warn_drv_unknown_argument_clang_cl
247 : diag::err_drv_unknown_argument;
248 Diags.Report(DiagID) << ArgString;
249 } else {
Simon Atanasyan27c0f202019-04-02 18:03:15 +0000250 DiagID = IsCLMode()
251 ? diag::warn_drv_unknown_argument_clang_cl_with_suggestion
252 : diag::err_drv_unknown_argument_with_suggestion;
Brian Gesiak24910762018-01-06 00:25:40 +0000253 Diags.Report(DiagID) << ArgString << Nearest;
254 }
255 ContainsError |= Diags.getDiagnosticLevel(DiagID, SourceLocation()) >
Benjamin Kramer43c0f482017-06-30 13:21:27 +0000256 DiagnosticsEngine::Warning;
257 }
Rafael Espindola8a2d4962013-09-23 23:55:25 +0000258
Daniel Dunbard02cb1d2009-03-05 06:38:47 +0000259 return Args;
260}
261
Chad Rosier7742b5d2011-07-27 23:36:45 +0000262// Determine which compilation mode we are in. We look for options which
263// affect the phase, starting with the earliest phases, and record which
264// option we used to determine the final phase.
Douglas Katzmana67e50c2015-06-26 15:47:46 +0000265phases::ID Driver::getFinalPhase(const DerivedArgList &DAL,
266 Arg **FinalPhaseArg) const {
Craig Topper92fc2df2014-05-17 16:56:41 +0000267 Arg *PhaseArg = nullptr;
Chad Rosier7742b5d2011-07-27 23:36:45 +0000268 phases::ID FinalPhase;
Eric Christopherf901e852011-08-17 22:59:59 +0000269
Hans Wennborge50cec32014-06-13 20:59:54 +0000270 // -{E,EP,P,M,MM} only run the preprocessor.
Douglas Katzmana67e50c2015-06-26 15:47:46 +0000271 if (CCCIsCPP() || (PhaseArg = DAL.getLastArg(options::OPT_E)) ||
Hans Wennborge50cec32014-06-13 20:59:54 +0000272 (PhaseArg = DAL.getLastArg(options::OPT__SLASH_EP)) ||
Hans Wennborge0053472013-12-20 18:40:46 +0000273 (PhaseArg = DAL.getLastArg(options::OPT_M, options::OPT_MM)) ||
274 (PhaseArg = DAL.getLastArg(options::OPT__SLASH_P))) {
Chad Rosier7742b5d2011-07-27 23:36:45 +0000275 FinalPhase = phases::Preprocess;
Eric Christopherf901e852011-08-17 22:59:59 +0000276
Richard Smithdd4ad3d2016-08-30 19:06:26 +0000277 // --precompile only runs up to precompilation.
278 } else if ((PhaseArg = DAL.getLastArg(options::OPT__precompile))) {
279 FinalPhase = phases::Precompile;
280
Bob Wilson23a55f12014-12-21 07:00:00 +0000281 // -{fsyntax-only,-analyze,emit-ast} only run up to the compiler.
Chad Rosier7742b5d2011-07-27 23:36:45 +0000282 } else if ((PhaseArg = DAL.getLastArg(options::OPT_fsyntax_only)) ||
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +0000283 (PhaseArg = DAL.getLastArg(options::OPT_module_file_info)) ||
Ben Langmuir2cb4a782014-02-05 22:21:15 +0000284 (PhaseArg = DAL.getLastArg(options::OPT_verify_pch)) ||
Chad Rosier7742b5d2011-07-27 23:36:45 +0000285 (PhaseArg = DAL.getLastArg(options::OPT_rewrite_objc)) ||
Fariborz Jahanian73223bb2012-04-02 15:59:19 +0000286 (PhaseArg = DAL.getLastArg(options::OPT_rewrite_legacy_objc)) ||
Ted Kremenekf7639e12012-03-06 20:06:33 +0000287 (PhaseArg = DAL.getLastArg(options::OPT__migrate)) ||
Chad Rosier7742b5d2011-07-27 23:36:45 +0000288 (PhaseArg = DAL.getLastArg(options::OPT__analyze,
Chad Rosier1aeb15a2012-03-06 23:14:35 +0000289 options::OPT__analyze_auto)) ||
Bob Wilson23a55f12014-12-21 07:00:00 +0000290 (PhaseArg = DAL.getLastArg(options::OPT_emit_ast))) {
Chad Rosier7742b5d2011-07-27 23:36:45 +0000291 FinalPhase = phases::Compile;
292
Bob Wilson23a55f12014-12-21 07:00:00 +0000293 // -S only runs up to the backend.
294 } else if ((PhaseArg = DAL.getLastArg(options::OPT_S))) {
295 FinalPhase = phases::Backend;
296
Artem Belevich4242f412015-07-28 21:01:21 +0000297 // -c compilation only runs up to the assembler.
298 } else if ((PhaseArg = DAL.getLastArg(options::OPT_c))) {
Chad Rosier7742b5d2011-07-27 23:36:45 +0000299 FinalPhase = phases::Assemble;
300
301 // Otherwise do everything.
302 } else
303 FinalPhase = phases::Link;
304
305 if (FinalPhaseArg)
306 *FinalPhaseArg = PhaseArg;
307
308 return FinalPhase;
309}
310
David Blaikie0aaa7622017-01-13 17:34:15 +0000311static Arg *MakeInputArg(DerivedArgList &Args, OptTable &Opts,
Martin Storsjo665c7a42018-05-04 06:05:58 +0000312 StringRef Value, bool Claim = true) {
David Blaikie0aaa7622017-01-13 17:34:15 +0000313 Arg *A = new Arg(Opts.getOption(options::OPT_INPUT), Value,
Hans Wennborged1d0722013-08-13 21:32:29 +0000314 Args.getBaseArgs().MakeIndex(Value), Value.data());
Hans Wennborg55362852014-05-02 22:55:30 +0000315 Args.AddSynthesizedArg(A);
Martin Storsjo665c7a42018-05-04 06:05:58 +0000316 if (Claim)
317 A->claim();
Hans Wennborged1d0722013-08-13 21:32:29 +0000318 return A;
319}
320
Daniel Dunbar775d4062010-06-11 22:00:26 +0000321DerivedArgList *Driver::TranslateInputArgs(const InputArgList &Args) const {
322 DerivedArgList *DAL = new DerivedArgList(Args);
323
Daniel Dunbar2cc3f172010-09-17 00:45:02 +0000324 bool HasNostdlib = Args.hasArg(options::OPT_nostdlib);
Dan Albertf5ffa1a2018-12-18 23:29:35 +0000325 bool HasNostdlibxx = Args.hasArg(options::OPT_nostdlibxx);
Nirav Daveb0bb6142015-11-24 16:07:21 +0000326 bool HasNodefaultlib = Args.hasArg(options::OPT_nodefaultlibs);
Saleem Abdulrasool688b6bc2014-12-29 19:01:36 +0000327 for (Arg *A : Args) {
Daniel Dunbarfb3d7472010-06-14 21:23:12 +0000328 // Unfortunately, we have to parse some forwarding options (-Xassembler,
329 // -Xlinker, -Xpreprocessor) because we either integrate their functionality
330 // (assembler and preprocessor), or bypass a previous driver ('collect2').
Daniel Dunbar5a9d1832010-06-14 21:37:09 +0000331
332 // Rewrite linker options, to replace --no-demangle with a custom internal
333 // option.
334 if ((A->getOption().matches(options::OPT_Wl_COMMA) ||
335 A->getOption().matches(options::OPT_Xlinker)) &&
336 A->containsValue("--no-demangle")) {
Daniel Dunbarfb3d7472010-06-14 21:23:12 +0000337 // Add the rewritten no-demangle argument.
338 DAL->AddFlagArg(A, Opts->getOption(options::OPT_Z_Xlinker__no_demangle));
339
340 // Add the remaining values as Xlinker arguments.
Benjamin Kramer72e64312015-09-24 14:48:49 +0000341 for (StringRef Val : A->getValues())
Douglas Katzmana34b7bf2015-06-30 19:32:57 +0000342 if (Val != "--no-demangle")
343 DAL->AddSeparateArg(A, Opts->getOption(options::OPT_Xlinker), Val);
Daniel Dunbarfb3d7472010-06-14 21:23:12 +0000344
345 continue;
346 }
347
Daniel Dunbar5a9d1832010-06-14 21:37:09 +0000348 // Rewrite preprocessor options, to replace -Wp,-MD,FOO which is used by
349 // some build systems. We don't try to be complete here because we don't
350 // care to encourage this usage model.
351 if (A->getOption().matches(options::OPT_Wp_COMMA) &&
Richard Smithbd55daf2012-11-01 04:30:05 +0000352 (A->getValue(0) == StringRef("-MD") ||
353 A->getValue(0) == StringRef("-MMD"))) {
Daniel Dunbar3648ba72010-06-15 20:30:18 +0000354 // Rewrite to -MD/-MMD along with -MF.
Richard Smithbd55daf2012-11-01 04:30:05 +0000355 if (A->getValue(0) == StringRef("-MD"))
Daniel Dunbar3648ba72010-06-15 20:30:18 +0000356 DAL->AddFlagArg(A, Opts->getOption(options::OPT_MD));
357 else
358 DAL->AddFlagArg(A, Opts->getOption(options::OPT_MMD));
Michael J. Spencer70d85be2012-11-07 23:37:14 +0000359 if (A->getNumValues() == 2)
360 DAL->AddSeparateArg(A, Opts->getOption(options::OPT_MF),
361 A->getValue(1));
Daniel Dunbar5a9d1832010-06-14 21:37:09 +0000362 continue;
363 }
364
Shantonu Senafeb03b2010-09-17 18:39:08 +0000365 // Rewrite reserved library names.
366 if (A->getOption().matches(options::OPT_l)) {
Richard Smithbd55daf2012-11-01 04:30:05 +0000367 StringRef Value = A->getValue();
Daniel Dunbar2cc3f172010-09-17 00:45:02 +0000368
Shantonu Senafeb03b2010-09-17 18:39:08 +0000369 // Rewrite unless -nostdlib is present.
Dan Albertf5ffa1a2018-12-18 23:29:35 +0000370 if (!HasNostdlib && !HasNodefaultlib && !HasNostdlibxx &&
371 Value == "stdc++") {
Douglas Katzmana67e50c2015-06-26 15:47:46 +0000372 DAL->AddFlagArg(A, Opts->getOption(options::OPT_Z_reserved_lib_stdcxx));
Daniel Dunbar2cc3f172010-09-17 00:45:02 +0000373 continue;
374 }
Shantonu Senafeb03b2010-09-17 18:39:08 +0000375
376 // Rewrite unconditionally.
377 if (Value == "cc_kext") {
Douglas Katzmana67e50c2015-06-26 15:47:46 +0000378 DAL->AddFlagArg(A, Opts->getOption(options::OPT_Z_reserved_lib_cckext));
Shantonu Senafeb03b2010-09-17 18:39:08 +0000379 continue;
380 }
Daniel Dunbar2cc3f172010-09-17 00:45:02 +0000381 }
382
Hans Wennborged1d0722013-08-13 21:32:29 +0000383 // Pick up inputs via the -- option.
384 if (A->getOption().matches(options::OPT__DASH_DASH)) {
385 A->claim();
Benjamin Kramer72e64312015-09-24 14:48:49 +0000386 for (StringRef Val : A->getValues())
Martin Storsjo665c7a42018-05-04 06:05:58 +0000387 DAL->append(MakeInputArg(*DAL, *Opts, Val, false));
Hans Wennborged1d0722013-08-13 21:32:29 +0000388 continue;
389 }
390
Saleem Abdulrasool688b6bc2014-12-29 19:01:36 +0000391 DAL->append(A);
Daniel Dunbarfb3d7472010-06-14 21:23:12 +0000392 }
Daniel Dunbar775d4062010-06-11 22:00:26 +0000393
Andrey Turetskiy6a8b91d2016-04-21 10:16:48 +0000394 // Enforce -static if -miamcu is present.
Andrey Turetskiy5fea71c2016-06-29 10:57:17 +0000395 if (Args.hasFlag(options::OPT_miamcu, options::OPT_mno_iamcu, false))
396 DAL->AddFlagArg(0, Opts->getOption(options::OPT_static));
Andrey Turetskiy6a8b91d2016-04-21 10:16:48 +0000397
Douglas Katzmana67e50c2015-06-26 15:47:46 +0000398// Add a default value of -mlinker-version=, if one was given and the user
399// didn't specify one.
Daniel Dunbar628fcf42010-08-12 00:05:12 +0000400#if defined(HOST_LINK_VERSION)
Tim Northover018578c2015-06-12 19:21:35 +0000401 if (!Args.hasArg(options::OPT_mlinker_version_EQ) &&
402 strlen(HOST_LINK_VERSION) > 0) {
Daniel Dunbar628fcf42010-08-12 00:05:12 +0000403 DAL->AddJoinedArg(0, Opts->getOption(options::OPT_mlinker_version_EQ),
404 HOST_LINK_VERSION);
Daniel Dunbarb613ffc2010-08-17 22:32:45 +0000405 DAL->getLastArg(options::OPT_mlinker_version_EQ)->claim();
Daniel Dunbar628fcf42010-08-12 00:05:12 +0000406 }
407#endif
408
Daniel Dunbar775d4062010-06-11 22:00:26 +0000409 return DAL;
410}
411
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000412/// Compute target triple from args.
Artem Belevich959e0542015-07-10 19:47:55 +0000413///
414/// This routine provides the logic to compute a target triple from various
415/// args passed to the driver and the default triple string.
Andrey Turetskiy6a8b91d2016-04-21 10:16:48 +0000416static llvm::Triple computeTargetTriple(const Driver &D,
Petr Hosekdd38d932018-05-29 22:35:39 +0000417 StringRef TargetTriple,
Artem Belevich959e0542015-07-10 19:47:55 +0000418 const ArgList &Args,
419 StringRef DarwinArchName = "") {
420 // FIXME: Already done in Compilation *Driver::BuildCompilation
421 if (const Arg *A = Args.getLastArg(options::OPT_target))
Petr Hosekdd38d932018-05-29 22:35:39 +0000422 TargetTriple = A->getValue();
Artem Belevich959e0542015-07-10 19:47:55 +0000423
Petr Hosekdd38d932018-05-29 22:35:39 +0000424 llvm::Triple Target(llvm::Triple::normalize(TargetTriple));
Artem Belevich959e0542015-07-10 19:47:55 +0000425
Kristina Brooks77a4adc2018-11-29 03:49:14 +0000426 // GNU/Hurd's triples should have been -hurd-gnu*, but were historically made
427 // -gnu* only, and we can not change this, so we have to detect that case as
428 // being the Hurd OS.
429 if (TargetTriple.find("-unknown-gnu") != StringRef::npos ||
430 TargetTriple.find("-pc-gnu") != StringRef::npos)
431 Target.setOSName("hurd");
432
Artem Belevich959e0542015-07-10 19:47:55 +0000433 // Handle Apple-specific options available here.
434 if (Target.isOSBinFormatMachO()) {
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +0000435 // If an explicit Darwin arch name is given, that trumps all.
Artem Belevich959e0542015-07-10 19:47:55 +0000436 if (!DarwinArchName.empty()) {
437 tools::darwin::setTripleTypeForMachOArchName(Target, DarwinArchName);
438 return Target;
439 }
440
441 // Handle the Darwin '-arch' flag.
442 if (Arg *A = Args.getLastArg(options::OPT_arch)) {
443 StringRef ArchName = A->getValue();
444 tools::darwin::setTripleTypeForMachOArchName(Target, ArchName);
445 }
446 }
447
448 // Handle pseudo-target flags '-mlittle-endian'/'-EL' and
449 // '-mbig-endian'/'-EB'.
450 if (Arg *A = Args.getLastArg(options::OPT_mlittle_endian,
451 options::OPT_mbig_endian)) {
452 if (A->getOption().matches(options::OPT_mlittle_endian)) {
453 llvm::Triple LE = Target.getLittleEndianArchVariant();
454 if (LE.getArch() != llvm::Triple::UnknownArch)
455 Target = std::move(LE);
456 } else {
457 llvm::Triple BE = Target.getBigEndianArchVariant();
458 if (BE.getArch() != llvm::Triple::UnknownArch)
459 Target = std::move(BE);
460 }
461 }
462
463 // Skip further flag support on OSes which don't support '-m32' or '-m64'.
Douglas Katzman15a63ed2015-08-12 18:36:12 +0000464 if (Target.getArch() == llvm::Triple::tce ||
465 Target.getOS() == llvm::Triple::Minix)
Artem Belevich959e0542015-07-10 19:47:55 +0000466 return Target;
467
468 // Handle pseudo-target flags '-m64', '-mx32', '-m32' and '-m16'.
Andrey Turetskiy6a8b91d2016-04-21 10:16:48 +0000469 Arg *A = Args.getLastArg(options::OPT_m64, options::OPT_mx32,
470 options::OPT_m32, options::OPT_m16);
471 if (A) {
Artem Belevich959e0542015-07-10 19:47:55 +0000472 llvm::Triple::ArchType AT = llvm::Triple::UnknownArch;
473
474 if (A->getOption().matches(options::OPT_m64)) {
475 AT = Target.get64BitArchVariant().getArch();
476 if (Target.getEnvironment() == llvm::Triple::GNUX32)
477 Target.setEnvironment(llvm::Triple::GNU);
478 } else if (A->getOption().matches(options::OPT_mx32) &&
479 Target.get64BitArchVariant().getArch() == llvm::Triple::x86_64) {
480 AT = llvm::Triple::x86_64;
481 Target.setEnvironment(llvm::Triple::GNUX32);
482 } else if (A->getOption().matches(options::OPT_m32)) {
483 AT = Target.get32BitArchVariant().getArch();
484 if (Target.getEnvironment() == llvm::Triple::GNUX32)
485 Target.setEnvironment(llvm::Triple::GNU);
486 } else if (A->getOption().matches(options::OPT_m16) &&
487 Target.get32BitArchVariant().getArch() == llvm::Triple::x86) {
488 AT = llvm::Triple::x86;
489 Target.setEnvironment(llvm::Triple::CODE16);
490 }
491
492 if (AT != llvm::Triple::UnknownArch && AT != Target.getArch())
493 Target.setArch(AT);
494 }
495
Andrey Turetskiy6a8b91d2016-04-21 10:16:48 +0000496 // Handle -miamcu flag.
Andrey Turetskiy5fea71c2016-06-29 10:57:17 +0000497 if (Args.hasFlag(options::OPT_miamcu, options::OPT_mno_iamcu, false)) {
498 if (Target.get32BitArchVariant().getArch() != llvm::Triple::x86)
499 D.Diag(diag::err_drv_unsupported_opt_for_target) << "-miamcu"
500 << Target.str();
Andrey Turetskiy6a8b91d2016-04-21 10:16:48 +0000501
Andrey Turetskiy5fea71c2016-06-29 10:57:17 +0000502 if (A && !A->getOption().matches(options::OPT_m32))
503 D.Diag(diag::err_drv_argument_not_allowed_with)
504 << "-miamcu" << A->getBaseArg().getAsString(Args);
Andrey Turetskiy6a8b91d2016-04-21 10:16:48 +0000505
Andrey Turetskiy5fea71c2016-06-29 10:57:17 +0000506 Target.setArch(llvm::Triple::x86);
507 Target.setArchName("i586");
508 Target.setEnvironment(llvm::Triple::UnknownEnvironment);
509 Target.setEnvironmentName("");
510 Target.setOS(llvm::Triple::ELFIAMCU);
511 Target.setVendor(llvm::Triple::UnknownVendor);
512 Target.setVendorName("intel");
Andrey Turetskiy6a8b91d2016-04-21 10:16:48 +0000513 }
514
Simon Atanasyan0c0fb4b2018-09-27 05:04:50 +0000515 // If target is MIPS adjust the target triple
516 // accordingly to provided ABI name.
517 A = Args.getLastArg(options::OPT_mabi_EQ);
Simon Atanasyane60eae42018-10-16 10:19:06 +0000518 if (A && Target.isMIPS()) {
519 StringRef ABIName = A->getValue();
520 if (ABIName == "32") {
521 Target = Target.get32BitArchVariant();
522 if (Target.getEnvironment() == llvm::Triple::GNUABI64 ||
523 Target.getEnvironment() == llvm::Triple::GNUABIN32)
524 Target.setEnvironment(llvm::Triple::GNU);
525 } else if (ABIName == "n32") {
526 Target = Target.get64BitArchVariant();
527 if (Target.getEnvironment() == llvm::Triple::GNU ||
528 Target.getEnvironment() == llvm::Triple::GNUABI64)
529 Target.setEnvironment(llvm::Triple::GNUABIN32);
530 } else if (ABIName == "64") {
531 Target = Target.get64BitArchVariant();
532 if (Target.getEnvironment() == llvm::Triple::GNU ||
533 Target.getEnvironment() == llvm::Triple::GNUABIN32)
534 Target.setEnvironment(llvm::Triple::GNUABI64);
535 }
536 }
Simon Atanasyan0c0fb4b2018-09-27 05:04:50 +0000537
Artem Belevich959e0542015-07-10 19:47:55 +0000538 return Target;
539}
540
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000541// Parse the LTO options and record the type of LTO compilation
Teresa Johnson945bc502015-10-15 20:35:53 +0000542// based on which -f(no-)?lto(=.*)? option occurs last.
543void Driver::setLTOMode(const llvm::opt::ArgList &Args) {
544 LTOMode = LTOK_None;
545 if (!Args.hasFlag(options::OPT_flto, options::OPT_flto_EQ,
546 options::OPT_fno_lto, false))
547 return;
548
549 StringRef LTOName("full");
550
551 const Arg *A = Args.getLastArg(options::OPT_flto_EQ);
Teresa Johnson6ef80dc2015-11-02 18:03:12 +0000552 if (A)
553 LTOName = A->getValue();
Teresa Johnson945bc502015-10-15 20:35:53 +0000554
555 LTOMode = llvm::StringSwitch<LTOKind>(LTOName)
556 .Case("full", LTOK_Full)
557 .Case("thin", LTOK_Thin)
558 .Default(LTOK_Unknown);
559
560 if (LTOMode == LTOK_Unknown) {
561 assert(A);
562 Diag(diag::err_drv_unsupported_option_argument) << A->getOption().getName()
563 << A->getValue();
564 }
565}
566
Samuel Antao39f9da22016-10-27 16:38:05 +0000567/// Compute the desired OpenMP runtime from the flags provided.
568Driver::OpenMPRuntimeKind Driver::getOpenMPRuntime(const ArgList &Args) const {
569 StringRef RuntimeName(CLANG_DEFAULT_OPENMP_RUNTIME);
570
571 const Arg *A = Args.getLastArg(options::OPT_fopenmp_EQ);
572 if (A)
573 RuntimeName = A->getValue();
574
575 auto RT = llvm::StringSwitch<OpenMPRuntimeKind>(RuntimeName)
576 .Case("libomp", OMPRT_OMP)
577 .Case("libgomp", OMPRT_GOMP)
578 .Case("libiomp5", OMPRT_IOMP5)
579 .Default(OMPRT_Unknown);
580
581 if (RT == OMPRT_Unknown) {
582 if (A)
583 Diag(diag::err_drv_unsupported_option_argument)
584 << A->getOption().getName() << A->getValue();
585 else
586 // FIXME: We could use a nicer diagnostic here.
587 Diag(diag::err_drv_unsupported_opt) << "-fopenmp";
588 }
589
590 return RT;
591}
592
Samuel Antaoc1ffba52016-06-13 18:10:57 +0000593void Driver::CreateOffloadingDeviceToolChains(Compilation &C,
594 InputList &Inputs) {
595
596 //
Yaxun Liuf5a6b962018-05-11 19:21:39 +0000597 // CUDA/HIP
Samuel Antaoc1ffba52016-06-13 18:10:57 +0000598 //
Yaxun Liuf6144222018-05-30 00:53:50 +0000599 // We need to generate a CUDA/HIP toolchain if any of the inputs has a CUDA
Yaxun Liuf5a6b962018-05-11 19:21:39 +0000600 // or HIP type. However, mixed CUDA/HIP compilation is not supported.
601 bool IsCuda =
602 llvm::any_of(Inputs, [](std::pair<types::ID, const llvm::opt::Arg *> &I) {
Samuel Antaoc1ffba52016-06-13 18:10:57 +0000603 return types::isCuda(I.first);
Yaxun Liuf5a6b962018-05-11 19:21:39 +0000604 });
605 bool IsHIP =
606 llvm::any_of(Inputs,
607 [](std::pair<types::ID, const llvm::opt::Arg *> &I) {
608 return types::isHIP(I.first);
609 }) ||
610 C.getInputArgs().hasArg(options::OPT_hip_link);
611 if (IsCuda && IsHIP) {
612 Diag(clang::diag::err_drv_mix_cuda_hip);
613 return;
614 }
Yaxun Liuf6144222018-05-30 00:53:50 +0000615 if (IsCuda) {
Justin Lebar66c4fd72016-11-18 00:41:22 +0000616 const ToolChain *HostTC = C.getSingleOffloadToolChain<Action::OFK_Host>();
617 const llvm::Triple &HostTriple = HostTC->getTriple();
Yaxun Liuf5a6b962018-05-11 19:21:39 +0000618 StringRef DeviceTripleStr;
Yaxun Liuf6144222018-05-30 00:53:50 +0000619 auto OFK = Action::OFK_Cuda;
620 DeviceTripleStr =
621 HostTriple.isArch64Bit() ? "nvptx64-nvidia-cuda" : "nvptx-nvidia-cuda";
Yaxun Liuf5a6b962018-05-11 19:21:39 +0000622 llvm::Triple CudaTriple(DeviceTripleStr);
Yaxun Liuf6144222018-05-30 00:53:50 +0000623 // Use the CUDA and host triples as the key into the ToolChains map,
Yaxun Liuf5a6b962018-05-11 19:21:39 +0000624 // because the device toolchain we create depends on both.
David Blaikie6ad71012017-01-13 18:53:43 +0000625 auto &CudaTC = ToolChains[CudaTriple.str() + "/" + HostTriple.str()];
Justin Lebar66c4fd72016-11-18 00:41:22 +0000626 if (!CudaTC) {
David Blaikie6ad71012017-01-13 18:53:43 +0000627 CudaTC = llvm::make_unique<toolchains::CudaToolChain>(
Yaxun Liuf5a6b962018-05-11 19:21:39 +0000628 *this, CudaTriple, *HostTC, C.getInputArgs(), OFK);
Justin Lebar66c4fd72016-11-18 00:41:22 +0000629 }
Yaxun Liuf5a6b962018-05-11 19:21:39 +0000630 C.addOffloadDeviceToolChain(CudaTC.get(), OFK);
Yaxun Liuf6144222018-05-30 00:53:50 +0000631 } else if (IsHIP) {
632 const ToolChain *HostTC = C.getSingleOffloadToolChain<Action::OFK_Host>();
633 const llvm::Triple &HostTriple = HostTC->getTriple();
634 StringRef DeviceTripleStr;
635 auto OFK = Action::OFK_HIP;
636 DeviceTripleStr = "amdgcn-amd-amdhsa";
637 llvm::Triple HIPTriple(DeviceTripleStr);
638 // Use the HIP and host triples as the key into the ToolChains map,
639 // because the device toolchain we create depends on both.
640 auto &HIPTC = ToolChains[HIPTriple.str() + "/" + HostTriple.str()];
641 if (!HIPTC) {
642 HIPTC = llvm::make_unique<toolchains::HIPToolChain>(
643 *this, HIPTriple, *HostTC, C.getInputArgs());
644 }
645 C.addOffloadDeviceToolChain(HIPTC.get(), OFK);
Samuel Antaoc1ffba52016-06-13 18:10:57 +0000646 }
647
648 //
Samuel Antao39f9da22016-10-27 16:38:05 +0000649 // OpenMP
650 //
651 // We need to generate an OpenMP toolchain if the user specified targets with
652 // the -fopenmp-targets option.
653 if (Arg *OpenMPTargets =
654 C.getInputArgs().getLastArg(options::OPT_fopenmp_targets_EQ)) {
655 if (OpenMPTargets->getNumValues()) {
656 // We expect that -fopenmp-targets is always used in conjunction with the
657 // option -fopenmp specifying a valid runtime with offloading support,
658 // i.e. libomp or libiomp.
659 bool HasValidOpenMPRuntime = C.getInputArgs().hasFlag(
660 options::OPT_fopenmp, options::OPT_fopenmp_EQ,
661 options::OPT_fno_openmp, false);
662 if (HasValidOpenMPRuntime) {
663 OpenMPRuntimeKind OpenMPKind = getOpenMPRuntime(C.getInputArgs());
664 HasValidOpenMPRuntime =
665 OpenMPKind == OMPRT_OMP || OpenMPKind == OMPRT_IOMP5;
666 }
667
668 if (HasValidOpenMPRuntime) {
669 llvm::StringMap<const char *> FoundNormalizedTriples;
670 for (const char *Val : OpenMPTargets->getValues()) {
671 llvm::Triple TT(Val);
672 std::string NormalizedName = TT.normalize();
673
674 // Make sure we don't have a duplicate triple.
675 auto Duplicate = FoundNormalizedTriples.find(NormalizedName);
676 if (Duplicate != FoundNormalizedTriples.end()) {
677 Diag(clang::diag::warn_drv_omp_offload_target_duplicate)
678 << Val << Duplicate->second;
679 continue;
680 }
681
682 // Store the current triple so that we can check for duplicates in the
683 // following iterations.
684 FoundNormalizedTriples[NormalizedName] = Val;
685
686 // If the specified target is invalid, emit a diagnostic.
687 if (TT.getArch() == llvm::Triple::UnknownArch)
688 Diag(clang::diag::err_drv_invalid_omp_target) << Val;
689 else {
Gheorghe-Teodor Bercea6a5df722017-07-06 16:08:15 +0000690 const ToolChain *TC;
691 // CUDA toolchains have to be selected differently. They pair host
692 // and device in their implementation.
693 if (TT.isNVPTX()) {
694 const ToolChain *HostTC =
695 C.getSingleOffloadToolChain<Action::OFK_Host>();
696 assert(HostTC && "Host toolchain should be always defined.");
697 auto &CudaTC =
Gheorghe-Teodor Bercea52898432017-08-09 01:02:19 +0000698 ToolChains[TT.str() + "/" + HostTC->getTriple().normalize()];
Gheorghe-Teodor Bercea6a5df722017-07-06 16:08:15 +0000699 if (!CudaTC)
700 CudaTC = llvm::make_unique<toolchains::CudaToolChain>(
Gheorghe-Teodor Bercea2c926932017-08-08 14:33:05 +0000701 *this, TT, *HostTC, C.getInputArgs(), Action::OFK_OpenMP);
Gheorghe-Teodor Bercea6a5df722017-07-06 16:08:15 +0000702 TC = CudaTC.get();
703 } else
704 TC = &getToolChain(C.getInputArgs(), TT);
705 C.addOffloadDeviceToolChain(TC, Action::OFK_OpenMP);
Samuel Antao39f9da22016-10-27 16:38:05 +0000706 }
707 }
708 } else
709 Diag(clang::diag::err_drv_expecting_fopenmp_with_fopenmp_targets);
710 } else
711 Diag(clang::diag::warn_drv_empty_joined_argument)
712 << OpenMPTargets->getAsString(C.getInputArgs());
713 }
714
715 //
Samuel Antaoc1ffba52016-06-13 18:10:57 +0000716 // TODO: Add support for other offloading programming models here.
717 //
Samuel Antaoc1ffba52016-06-13 18:10:57 +0000718}
719
Serge Pavlov208ac652018-01-01 13:27:01 +0000720/// Looks the given directories for the specified file.
721///
722/// \param[out] FilePath File path, if the file was found.
723/// \param[in] Dirs Directories used for the search.
724/// \param[in] FileName Name of the file to search for.
725/// \return True if file was found.
726///
727/// Looks for file specified by FileName sequentially in directories specified
728/// by Dirs.
729///
730static bool searchForFile(SmallVectorImpl<char> &FilePath,
731 ArrayRef<std::string> Dirs,
732 StringRef FileName) {
733 SmallString<128> WPath;
734 for (const StringRef &Dir : Dirs) {
735 if (Dir.empty())
736 continue;
737 WPath.clear();
738 llvm::sys::path::append(WPath, Dir, FileName);
739 llvm::sys::path::native(WPath);
740 if (llvm::sys::fs::is_regular_file(WPath)) {
741 FilePath = std::move(WPath);
742 return true;
743 }
744 }
745 return false;
746}
747
748bool Driver::readConfigFile(StringRef FileName) {
749 // Try reading the given file.
750 SmallVector<const char *, 32> NewCfgArgs;
751 if (!llvm::cl::readConfigFile(FileName, Saver, NewCfgArgs)) {
752 Diag(diag::err_drv_cannot_read_config_file) << FileName;
753 return true;
754 }
755
756 // Read options from config file.
757 llvm::SmallString<128> CfgFileName(FileName);
758 llvm::sys::path::native(CfgFileName);
759 ConfigFile = CfgFileName.str();
760 bool ContainErrors;
761 CfgOptions = llvm::make_unique<InputArgList>(
Hans Wennborg797004d2018-11-08 11:27:04 +0000762 ParseArgStrings(NewCfgArgs, IsCLMode(), ContainErrors));
Serge Pavlov208ac652018-01-01 13:27:01 +0000763 if (ContainErrors) {
764 CfgOptions.reset();
765 return true;
766 }
767
768 if (CfgOptions->hasArg(options::OPT_config)) {
769 CfgOptions.reset();
770 Diag(diag::err_drv_nested_config_file);
771 return true;
772 }
773
774 // Claim all arguments that come from a configuration file so that the driver
775 // does not warn on any that is unused.
776 for (Arg *A : *CfgOptions)
777 A->claim();
778 return false;
779}
780
781bool Driver::loadConfigFile() {
782 std::string CfgFileName;
783 bool FileSpecifiedExplicitly = false;
784
785 // Process options that change search path for config files.
786 if (CLOptions) {
787 if (CLOptions->hasArg(options::OPT_config_system_dir_EQ)) {
788 SmallString<128> CfgDir;
789 CfgDir.append(
790 CLOptions->getLastArgValue(options::OPT_config_system_dir_EQ));
791 if (!CfgDir.empty()) {
Sam McCall296d8322018-01-02 09:35:10 +0000792 if (llvm::sys::fs::make_absolute(CfgDir).value() != 0)
Serge Pavlov208ac652018-01-01 13:27:01 +0000793 SystemConfigDir.clear();
794 else
795 SystemConfigDir = std::string(CfgDir.begin(), CfgDir.end());
796 }
797 }
798 if (CLOptions->hasArg(options::OPT_config_user_dir_EQ)) {
799 SmallString<128> CfgDir;
800 CfgDir.append(
801 CLOptions->getLastArgValue(options::OPT_config_user_dir_EQ));
802 if (!CfgDir.empty()) {
Sam McCall296d8322018-01-02 09:35:10 +0000803 if (llvm::sys::fs::make_absolute(CfgDir).value() != 0)
Serge Pavlov208ac652018-01-01 13:27:01 +0000804 UserConfigDir.clear();
805 else
806 UserConfigDir = std::string(CfgDir.begin(), CfgDir.end());
807 }
808 }
809 }
810
811 // First try to find config file specified in command line.
812 if (CLOptions) {
813 std::vector<std::string> ConfigFiles =
814 CLOptions->getAllArgValues(options::OPT_config);
815 if (ConfigFiles.size() > 1) {
816 Diag(diag::err_drv_duplicate_config);
817 return true;
818 }
819
820 if (!ConfigFiles.empty()) {
821 CfgFileName = ConfigFiles.front();
822 assert(!CfgFileName.empty());
823
824 // If argument contains directory separator, treat it as a path to
825 // configuration file.
826 if (llvm::sys::path::has_parent_path(CfgFileName)) {
827 SmallString<128> CfgFilePath;
828 if (llvm::sys::path::is_relative(CfgFileName))
829 llvm::sys::fs::current_path(CfgFilePath);
830 llvm::sys::path::append(CfgFilePath, CfgFileName);
831 if (!llvm::sys::fs::is_regular_file(CfgFilePath)) {
832 Diag(diag::err_drv_config_file_not_exist) << CfgFilePath;
833 return true;
834 }
835 return readConfigFile(CfgFilePath);
836 }
837
838 FileSpecifiedExplicitly = true;
839 }
840 }
841
842 // If config file is not specified explicitly, try to deduce configuration
843 // from executable name. For instance, an executable 'armv7l-clang' will
844 // search for config file 'armv7l-clang.cfg'.
845 if (CfgFileName.empty() && !ClangNameParts.TargetPrefix.empty())
846 CfgFileName = ClangNameParts.TargetPrefix + '-' + ClangNameParts.ModeSuffix;
847
848 if (CfgFileName.empty())
849 return false;
850
851 // Determine architecture part of the file name, if it is present.
852 StringRef CfgFileArch = CfgFileName;
853 size_t ArchPrefixLen = CfgFileArch.find('-');
854 if (ArchPrefixLen == StringRef::npos)
855 ArchPrefixLen = CfgFileArch.size();
856 llvm::Triple CfgTriple;
857 CfgFileArch = CfgFileArch.take_front(ArchPrefixLen);
858 CfgTriple = llvm::Triple(llvm::Triple::normalize(CfgFileArch));
859 if (CfgTriple.getArch() == llvm::Triple::ArchType::UnknownArch)
860 ArchPrefixLen = 0;
861
862 if (!StringRef(CfgFileName).endswith(".cfg"))
863 CfgFileName += ".cfg";
864
865 // If config file starts with architecture name and command line options
866 // redefine architecture (with options like -m32 -LE etc), try finding new
867 // config file with that architecture.
868 SmallString<128> FixedConfigFile;
869 size_t FixedArchPrefixLen = 0;
870 if (ArchPrefixLen) {
871 // Get architecture name from config file name like 'i386.cfg' or
872 // 'armv7l-clang.cfg'.
873 // Check if command line options changes effective triple.
874 llvm::Triple EffectiveTriple = computeTargetTriple(*this,
875 CfgTriple.getTriple(), *CLOptions);
876 if (CfgTriple.getArch() != EffectiveTriple.getArch()) {
877 FixedConfigFile = EffectiveTriple.getArchName();
878 FixedArchPrefixLen = FixedConfigFile.size();
879 // Append the rest of original file name so that file name transforms
880 // like: i386-clang.cfg -> x86_64-clang.cfg.
881 if (ArchPrefixLen < CfgFileName.size())
882 FixedConfigFile += CfgFileName.substr(ArchPrefixLen);
883 }
884 }
885
886 // Prepare list of directories where config file is searched for.
887 SmallVector<std::string, 3> CfgFileSearchDirs;
888 CfgFileSearchDirs.push_back(UserConfigDir);
889 CfgFileSearchDirs.push_back(SystemConfigDir);
890 CfgFileSearchDirs.push_back(Dir);
891
892 // Try to find config file. First try file with corrected architecture.
893 llvm::SmallString<128> CfgFilePath;
894 if (!FixedConfigFile.empty()) {
895 if (searchForFile(CfgFilePath, CfgFileSearchDirs, FixedConfigFile))
896 return readConfigFile(CfgFilePath);
897 // If 'x86_64-clang.cfg' was not found, try 'x86_64.cfg'.
898 FixedConfigFile.resize(FixedArchPrefixLen);
899 FixedConfigFile.append(".cfg");
900 if (searchForFile(CfgFilePath, CfgFileSearchDirs, FixedConfigFile))
901 return readConfigFile(CfgFilePath);
902 }
903
904 // Then try original file name.
905 if (searchForFile(CfgFilePath, CfgFileSearchDirs, CfgFileName))
906 return readConfigFile(CfgFilePath);
907
908 // Finally try removing driver mode part: 'x86_64-clang.cfg' -> 'x86_64.cfg'.
909 if (!ClangNameParts.ModeSuffix.empty() &&
910 !ClangNameParts.TargetPrefix.empty()) {
911 CfgFileName.assign(ClangNameParts.TargetPrefix);
912 CfgFileName.append(".cfg");
913 if (searchForFile(CfgFilePath, CfgFileSearchDirs, CfgFileName))
914 return readConfigFile(CfgFilePath);
915 }
916
917 // Report error but only if config file was specified explicitly, by option
918 // --config. If it was deduced from executable name, it is not an error.
919 if (FileSpecifiedExplicitly) {
920 Diag(diag::err_drv_config_file_not_found) << CfgFileName;
921 for (const std::string &SearchDir : CfgFileSearchDirs)
922 if (!SearchDir.empty())
923 Diag(diag::note_drv_config_file_searched_in) << SearchDir;
924 return true;
925 }
926
927 return false;
928}
929
Chris Lattner54b16772011-07-23 17:14:25 +0000930Compilation *Driver::BuildCompilation(ArrayRef<const char *> ArgList) {
Daniel Dunbar2608c542009-03-18 01:38:48 +0000931 llvm::PrettyStackTraceString CrashInfo("Compilation construction");
932
Eric Christopherf901e852011-08-17 22:59:59 +0000933 // FIXME: Handle environment options which affect driver behavior, somewhere
Bill Wendlingadbeb9f2012-03-12 21:24:57 +0000934 // (client?). GCC_EXEC_PREFIX, LPATH, CC_PRINT_OPTIONS.
Chad Rosier82301162011-09-14 00:47:55 +0000935
David Majnemer85c25b42016-07-24 17:44:03 +0000936 if (Optional<std::string> CompilerPathValue =
937 llvm::sys::Process::GetEnv("COMPILER_PATH")) {
938 StringRef CompilerPath = *CompilerPathValue;
Chad Rosier82301162011-09-14 00:47:55 +0000939 while (!CompilerPath.empty()) {
Douglas Katzmana67e50c2015-06-26 15:47:46 +0000940 std::pair<StringRef, StringRef> Split =
941 CompilerPath.split(llvm::sys::EnvPathSeparator);
Chad Rosier82301162011-09-14 00:47:55 +0000942 PrefixDirs.push_back(Split.first);
943 CompilerPath = Split.second;
944 }
945 }
Daniel Dunbar5e0f6af2009-03-13 00:51:18 +0000946
Hans Wennborg70850d82013-07-18 20:29:38 +0000947 // We look for the driver mode option early, because the mode can affect
948 // how other options are parsed.
Zachary Turneraff19c32016-08-12 17:47:52 +0000949 ParseDriverMode(ClangExecutable, ArgList.slice(1));
Hans Wennborg70850d82013-07-18 20:29:38 +0000950
Daniel Dunbar5e0f6af2009-03-13 00:51:18 +0000951 // FIXME: What are we going to do with -V and -b?
952
Serge Pavlov208ac652018-01-01 13:27:01 +0000953 // Arguments specified in command line.
954 bool ContainsError;
955 CLOptions = llvm::make_unique<InputArgList>(
Hans Wennborg797004d2018-11-08 11:27:04 +0000956 ParseArgStrings(ArgList.slice(1), IsCLMode(), ContainsError));
Serge Pavlov208ac652018-01-01 13:27:01 +0000957
958 // Try parsing configuration file.
959 if (!ContainsError)
960 ContainsError = loadConfigFile();
961 bool HasConfigFile = !ContainsError && (CfgOptions.get() != nullptr);
962
963 // All arguments, from both config file and command line.
964 InputArgList Args = std::move(HasConfigFile ? std::move(*CfgOptions)
965 : std::move(*CLOptions));
Hans Wennborg797004d2018-11-08 11:27:04 +0000966
967 auto appendOneArg = [&Args](const Arg *Opt, const Arg *BaseArg) {
Serge Pavlovf015a562018-04-26 06:28:47 +0000968 unsigned Index = Args.MakeIndex(Opt->getSpelling());
Serge Pavlov208ac652018-01-01 13:27:01 +0000969 Arg *Copy = new llvm::opt::Arg(Opt->getOption(), Opt->getSpelling(),
Serge Pavlovf015a562018-04-26 06:28:47 +0000970 Index, BaseArg);
Serge Pavlov208ac652018-01-01 13:27:01 +0000971 Copy->getValues() = Opt->getValues();
972 if (Opt->isClaimed())
973 Copy->claim();
974 Args.append(Copy);
Hans Wennborg797004d2018-11-08 11:27:04 +0000975 };
976
977 if (HasConfigFile)
978 for (auto *Opt : *CLOptions) {
979 if (Opt->getOption().matches(options::OPT_config))
980 continue;
981 const Arg *BaseArg = &Opt->getBaseArg();
982 if (BaseArg == Opt)
983 BaseArg = nullptr;
984 appendOneArg(Opt, BaseArg);
Serge Pavlov208ac652018-01-01 13:27:01 +0000985 }
986
Hans Wennborg797004d2018-11-08 11:27:04 +0000987 // In CL mode, look for any pass-through arguments
988 if (IsCLMode() && !ContainsError) {
989 SmallVector<const char *, 16> CLModePassThroughArgList;
990 for (const auto *A : Args.filtered(options::OPT__SLASH_clang)) {
991 A->claim();
992 CLModePassThroughArgList.push_back(A->getValue());
993 }
994
995 if (!CLModePassThroughArgList.empty()) {
996 // Parse any pass through args using default clang processing rather
997 // than clang-cl processing.
998 auto CLModePassThroughOptions = llvm::make_unique<InputArgList>(
999 ParseArgStrings(CLModePassThroughArgList, false, ContainsError));
1000
1001 if (!ContainsError)
1002 for (auto *Opt : *CLModePassThroughOptions) {
1003 appendOneArg(Opt, nullptr);
1004 }
1005 }
1006 }
1007
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001008 // FIXME: This stuff needs to go into the Compilation, not the driver.
Douglas Katzmanb7e8ef02015-06-25 19:37:41 +00001009 bool CCCPrintPhases;
Daniel Dunbard02cb1d2009-03-05 06:38:47 +00001010
Filipe Cabecinhas136f35e2015-07-18 06:35:24 +00001011 // Silence driver warnings if requested
1012 Diags.setIgnoreAllWarnings(Args.hasArg(options::OPT_w));
1013
Rafael Espindola59ae7992009-12-07 18:28:29 +00001014 // -no-canonical-prefixes is used very early in main.
David Blaikie69a1d8c2015-06-22 22:07:27 +00001015 Args.ClaimAllArgs(options::OPT_no_canonical_prefixes);
Rafael Espindola59ae7992009-12-07 18:28:29 +00001016
Daniel Dunbar926f81f2010-08-02 02:38:03 +00001017 // Ignore -pipe.
David Blaikie69a1d8c2015-06-22 22:07:27 +00001018 Args.ClaimAllArgs(options::OPT_pipe);
Daniel Dunbar926f81f2010-08-02 02:38:03 +00001019
Daniel Dunbaracd69572009-12-04 21:55:23 +00001020 // Extract -ccc args.
Daniel Dunbaree66cf22009-03-10 20:52:46 +00001021 //
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001022 // FIXME: We need to figure out where this behavior should live. Most of it
1023 // should be outside in the client; the parts that aren't should have proper
1024 // options, either by introducing new ones or by overloading gcc ones like -V
1025 // or -b.
Douglas Katzmanb7e8ef02015-06-25 19:37:41 +00001026 CCCPrintPhases = Args.hasArg(options::OPT_ccc_print_phases);
David Blaikie69a1d8c2015-06-22 22:07:27 +00001027 CCCPrintBindings = Args.hasArg(options::OPT_ccc_print_bindings);
1028 if (const Arg *A = Args.getLastArg(options::OPT_ccc_gcc_name))
Richard Smithbd55daf2012-11-01 04:30:05 +00001029 CCCGenericGCCName = A->getValue();
Bruno Cardoso Lopes52dfe712017-04-12 21:46:20 +00001030 GenReproducer = Args.hasFlag(options::OPT_gen_reproducer,
1031 options::OPT_fno_crash_diagnostics,
1032 !!::getenv("FORCE_CLANG_DIAGNOSTICS_CRASH"));
Petr Hosekdd38d932018-05-29 22:35:39 +00001033 // FIXME: TargetTriple is used by the target-prefixed calls to as/ld
Joerg Sonnenberger17d75512012-02-22 19:15:16 +00001034 // and getToolChain is const.
Hans Wennborg2e274592013-08-13 23:38:57 +00001035 if (IsCLMode()) {
Hans Wennborg73609a02014-03-28 01:19:04 +00001036 // clang-cl targets MSVC-style Win32.
Petr Hosekdd38d932018-05-29 22:35:39 +00001037 llvm::Triple T(TargetTriple);
Hans Wennborg9d9ce7a2014-03-28 20:49:28 +00001038 T.setOS(llvm::Triple::Win32);
Hans Wennborg0f0e8d62015-09-18 17:11:50 +00001039 T.setVendor(llvm::Triple::PC);
Hans Wennborg9d9ce7a2014-03-28 20:49:28 +00001040 T.setEnvironment(llvm::Triple::MSVC);
Oleg Ranevskyy80523182017-08-31 20:31:30 +00001041 T.setObjectFormat(llvm::Triple::COFF);
Petr Hosekdd38d932018-05-29 22:35:39 +00001042 TargetTriple = T.str();
Hans Wennborg2e274592013-08-13 23:38:57 +00001043 }
David Blaikie69a1d8c2015-06-22 22:07:27 +00001044 if (const Arg *A = Args.getLastArg(options::OPT_target))
Petr Hosekdd38d932018-05-29 22:35:39 +00001045 TargetTriple = A->getValue();
David Blaikie69a1d8c2015-06-22 22:07:27 +00001046 if (const Arg *A = Args.getLastArg(options::OPT_ccc_install_dir))
Richard Smithbd55daf2012-11-01 04:30:05 +00001047 Dir = InstalledDir = A->getValue();
David Blaikie69a1d8c2015-06-22 22:07:27 +00001048 for (const Arg *A : Args.filtered(options::OPT_B)) {
Benjamin Kramer1a648d12011-02-08 20:31:42 +00001049 A->claim();
Richard Smithbd55daf2012-11-01 04:30:05 +00001050 PrefixDirs.push_back(A->getValue(0));
Benjamin Kramer1a648d12011-02-08 20:31:42 +00001051 }
David Blaikie69a1d8c2015-06-22 22:07:27 +00001052 if (const Arg *A = Args.getLastArg(options::OPT__sysroot_EQ))
Richard Smithbd55daf2012-11-01 04:30:05 +00001053 SysRoot = A->getValue();
David Blaikie69a1d8c2015-06-22 22:07:27 +00001054 if (const Arg *A = Args.getLastArg(options::OPT__dyld_prefix_EQ))
Peter Collingbourne9d9e1fc2013-05-27 21:40:20 +00001055 DyldPrefix = A->getValue();
Daniel Dunbaree66cf22009-03-10 20:52:46 +00001056
David Blaikie69a1d8c2015-06-22 22:07:27 +00001057 if (const Arg *A = Args.getLastArg(options::OPT_resource_dir))
Bob Wilsona20a1da2013-03-23 05:17:59 +00001058 ResourceDir = A->getValue();
Jim Grosbach061dabf2013-03-12 20:17:58 +00001059
David Blaikie69a1d8c2015-06-22 22:07:27 +00001060 if (const Arg *A = Args.getLastArg(options::OPT_save_temps_EQ)) {
Reid Kleckner68eb60b2015-02-02 22:41:48 +00001061 SaveTemps = llvm::StringSwitch<SaveTempsMode>(A->getValue())
1062 .Case("cwd", SaveTempsCwd)
1063 .Case("obj", SaveTempsObj)
1064 .Default(SaveTempsCwd);
1065 }
1066
Steven Wu1257cd82016-05-18 17:04:52 +00001067 setLTOMode(Args);
1068
Steven Wu844ab6a2016-11-16 06:06:44 +00001069 // Process -fembed-bitcode= flags.
1070 if (Arg *A = Args.getLastArg(options::OPT_fembed_bitcode_EQ)) {
1071 StringRef Name = A->getValue();
1072 unsigned Model = llvm::StringSwitch<unsigned>(Name)
1073 .Case("off", EmbedNone)
1074 .Case("all", EmbedBitcode)
1075 .Case("bitcode", EmbedBitcode)
1076 .Case("marker", EmbedMarker)
1077 .Default(~0U);
1078 if (Model == ~0U) {
1079 Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args)
1080 << Name;
1081 } else
1082 BitcodeEmbed = static_cast<BitcodeEmbedMode>(Model);
Steven Wu574b0f22016-03-01 01:07:58 +00001083 }
1084
David Blaikie69a1d8c2015-06-22 22:07:27 +00001085 std::unique_ptr<llvm::opt::InputArgList> UArgs =
1086 llvm::make_unique<InputArgList>(std::move(Args));
1087
Daniel Dunbar775d4062010-06-11 22:00:26 +00001088 // Perform the default argument translations.
David Blaikie69a1d8c2015-06-22 22:07:27 +00001089 DerivedArgList *TranslatedArgs = TranslateInputArgs(*UArgs);
Daniel Dunbar775d4062010-06-11 22:00:26 +00001090
Chandler Carruthcb916192012-01-25 08:49:21 +00001091 // Owned by the host.
Andrey Turetskiy6a8b91d2016-04-21 10:16:48 +00001092 const ToolChain &TC = getToolChain(
Petr Hosekdd38d932018-05-29 22:35:39 +00001093 *UArgs, computeTargetTriple(*this, TargetTriple, *UArgs));
Chandler Carruthcb916192012-01-25 08:49:21 +00001094
Daniel Dunbar3ce436d2009-03-16 06:42:30 +00001095 // The compilation takes ownership of Args.
Benjamin Kramer43c0f482017-06-30 13:21:27 +00001096 Compilation *C = new Compilation(*this, TC, UArgs.release(), TranslatedArgs,
1097 ContainsError);
Daniel Dunbarf0eddb82009-03-18 02:55:38 +00001098
Daniel Dunbarf0eddb82009-03-18 02:55:38 +00001099 if (!HandleImmediateArgs(*C))
1100 return C;
1101
Chad Rosierecdede82011-08-12 22:08:57 +00001102 // Construct the list of inputs.
1103 InputList Inputs;
Hans Wennborged1d0722013-08-13 21:32:29 +00001104 BuildInputs(C->getDefaultToolChain(), *TranslatedArgs, Inputs);
Chad Rosierecdede82011-08-12 22:08:57 +00001105
Samuel Antaoc1ffba52016-06-13 18:10:57 +00001106 // Populate the tool chains for the offloading devices, if any.
1107 CreateOffloadingDeviceToolChains(*C, Inputs);
Justin Lebar0e450a52016-03-30 23:30:25 +00001108
Chandler Carruth7f1417f2012-01-24 10:43:44 +00001109 // Construct the list of abstract actions to perform for this compilation. On
Tim Northover157d9112014-01-16 08:48:16 +00001110 // MachO targets this uses the driver-driver and universal actions.
1111 if (TC.getTriple().isOSBinFormatMachO())
Artem Belevich5e2a3ec2015-11-17 22:28:40 +00001112 BuildUniversalActions(*C, C->getDefaultToolChain(), Inputs);
Daniel Dunbarf0eddb82009-03-18 02:55:38 +00001113 else
Justin Lebar0f3474c2016-02-11 02:00:50 +00001114 BuildActions(*C, C->getArgs(), Inputs, C->getActions());
Daniel Dunbarf0eddb82009-03-18 02:55:38 +00001115
Douglas Katzmanb7e8ef02015-06-25 19:37:41 +00001116 if (CCCPrintPhases) {
Daniel Dunbareb843be2009-03-18 03:13:20 +00001117 PrintActions(*C);
Daniel Dunbarf0eddb82009-03-18 02:55:38 +00001118 return C;
1119 }
1120
1121 BuildJobs(*C);
Daniel Dunbaradc91e62009-03-15 01:38:15 +00001122
1123 return C;
Daniel Dunbaree66cf22009-03-10 20:52:46 +00001124}
1125
Justin Bognered9cbe02015-07-09 06:58:31 +00001126static void printArgList(raw_ostream &OS, const llvm::opt::ArgList &Args) {
1127 llvm::opt::ArgStringList ASL;
1128 for (const auto *A : Args)
1129 A->render(Args, ASL);
1130
1131 for (auto I = ASL.begin(), E = ASL.end(); I != E; ++I) {
1132 if (I != ASL.begin())
1133 OS << ' ';
1134 Command::printArg(OS, *I, true);
1135 }
1136 OS << '\n';
1137}
1138
Bruno Cardoso Lopes02681c42016-11-17 21:41:22 +00001139bool Driver::getCrashDiagnosticFile(StringRef ReproCrashFilename,
1140 SmallString<128> &CrashDiagDir) {
1141 using namespace llvm::sys;
1142 assert(llvm::Triple(llvm::sys::getProcessTriple()).isOSDarwin() &&
1143 "Only knows about .crash files on Darwin");
1144
1145 // The .crash file can be found on at ~/Library/Logs/DiagnosticReports/
1146 // (or /Library/Logs/DiagnosticReports for root) and has the filename pattern
1147 // clang-<VERSION>_<YYYY-MM-DD-HHMMSS>_<hostname>.crash.
1148 path::home_directory(CrashDiagDir);
1149 if (CrashDiagDir.startswith("/var/root"))
1150 CrashDiagDir = "/";
1151 path::append(CrashDiagDir, "Library/Logs/DiagnosticReports");
1152 int PID =
1153#if LLVM_ON_UNIX
1154 getpid();
1155#else
1156 0;
1157#endif
1158 std::error_code EC;
1159 fs::file_status FileStatus;
1160 TimePoint<> LastAccessTime;
1161 SmallString<128> CrashFilePath;
1162 // Lookup the .crash files and get the one generated by a subprocess spawned
1163 // by this driver invocation.
1164 for (fs::directory_iterator File(CrashDiagDir, EC), FileEnd;
1165 File != FileEnd && !EC; File.increment(EC)) {
1166 StringRef FileName = path::filename(File->path());
1167 if (!FileName.startswith(Name))
1168 continue;
1169 if (fs::status(File->path(), FileStatus))
1170 continue;
1171 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> CrashFile =
1172 llvm::MemoryBuffer::getFile(File->path());
1173 if (!CrashFile)
1174 continue;
1175 // The first line should start with "Process:", otherwise this isn't a real
1176 // .crash file.
1177 StringRef Data = CrashFile.get()->getBuffer();
1178 if (!Data.startswith("Process:"))
1179 continue;
1180 // Parse parent process pid line, e.g: "Parent Process: clang-4.0 [79141]"
1181 size_t ParentProcPos = Data.find("Parent Process:");
1182 if (ParentProcPos == StringRef::npos)
1183 continue;
1184 size_t LineEnd = Data.find_first_of("\n", ParentProcPos);
1185 if (LineEnd == StringRef::npos)
1186 continue;
1187 StringRef ParentProcess = Data.slice(ParentProcPos+15, LineEnd).trim();
1188 int OpenBracket = -1, CloseBracket = -1;
1189 for (size_t i = 0, e = ParentProcess.size(); i < e; ++i) {
1190 if (ParentProcess[i] == '[')
1191 OpenBracket = i;
1192 if (ParentProcess[i] == ']')
1193 CloseBracket = i;
1194 }
1195 // Extract the parent process PID from the .crash file and check whether
1196 // it matches this driver invocation pid.
1197 int CrashPID;
1198 if (OpenBracket < 0 || CloseBracket < 0 ||
1199 ParentProcess.slice(OpenBracket + 1, CloseBracket)
1200 .getAsInteger(10, CrashPID) || CrashPID != PID) {
1201 continue;
1202 }
1203
1204 // Found a .crash file matching the driver pid. To avoid getting an older
1205 // and misleading crash file, continue looking for the most recent.
1206 // FIXME: the driver can dispatch multiple cc1 invocations, leading to
1207 // multiple crashes poiting to the same parent process. Since the driver
1208 // does not collect pid information for the dispatched invocation there's
1209 // currently no way to distinguish among them.
1210 const auto FileAccessTime = FileStatus.getLastModificationTime();
1211 if (FileAccessTime > LastAccessTime) {
1212 CrashFilePath.assign(File->path());
1213 LastAccessTime = FileAccessTime;
1214 }
1215 }
1216
1217 // If found, copy it over to the location of other reproducer files.
1218 if (!CrashFilePath.empty()) {
1219 EC = fs::copy_file(CrashFilePath, ReproCrashFilename);
1220 if (EC)
1221 return false;
1222 return true;
1223 }
1224
1225 return false;
1226}
1227
Eric Christopherf901e852011-08-17 22:59:59 +00001228// When clang crashes, produce diagnostic information including the fully
1229// preprocessed source file(s). Request that the developer attach the
Chad Rosierbe10f982011-08-02 17:58:04 +00001230// diagnostic information to a bug report.
Alex Lorenz045c5142018-04-07 00:03:27 +00001231void Driver::generateCompilationDiagnostics(
1232 Compilation &C, const Command &FailingCommand,
1233 StringRef AdditionalInformation, CompilationDiagnosticReport *Report) {
Chad Rosier877c0a22012-02-22 00:30:39 +00001234 if (C.getArgs().hasArg(options::OPT_fno_crash_diagnostics))
Chad Rosier62135492012-07-09 17:31:28 +00001235 return;
Chad Rosierbee5a1d2012-03-07 00:30:40 +00001236
Chad Rosierdbf46a12013-02-01 18:30:26 +00001237 // Don't try to generate diagnostics for link or dsymutil jobs.
Justin Bognere1a33d12014-10-20 21:02:05 +00001238 if (FailingCommand.getCreator().isLinkJob() ||
1239 FailingCommand.getCreator().isDsymutilJob())
Chad Rosier877c0a22012-02-22 00:30:39 +00001240 return;
1241
Chad Rosier8179f112012-06-19 17:51:34 +00001242 // Print the version of the compiler.
1243 PrintVersion(C, llvm::errs());
1244
Chad Rosierbe10f982011-08-02 17:58:04 +00001245 Diag(clang::diag::note_drv_command_failed_diag_msg)
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001246 << "PLEASE submit a bug report to " BUG_REPORT_URL " and include the "
1247 "crash backtrace, preprocessed source, and associated run script.";
Chad Rosierbe10f982011-08-02 17:58:04 +00001248
1249 // Suppress driver output and emit preprocessor output to temp file.
Hans Wennborg70850d82013-07-18 20:29:38 +00001250 Mode = CPPMode;
Chad Rosierbe10f982011-08-02 17:58:04 +00001251 CCGenDiagnostics = true;
1252
Chad Rosiercdb008d2011-11-02 21:29:05 +00001253 // Save the original job command(s).
Justin Bogner25645152014-10-21 17:24:44 +00001254 Command Cmd = FailingCommand;
Chad Rosiercdb008d2011-11-02 21:29:05 +00001255
Richard Smith5bb4cdf2012-12-20 02:22:15 +00001256 // Keep track of whether we produce any errors while trying to produce
1257 // preprocessed sources.
1258 DiagnosticErrorTrap Trap(Diags);
1259
1260 // Suppress tool output.
Chad Rosierbe10f982011-08-02 17:58:04 +00001261 C.initCompilationForDiagnostics();
Chad Rosierecdede82011-08-12 22:08:57 +00001262
1263 // Construct the list of inputs.
1264 InputList Inputs;
1265 BuildInputs(C.getDefaultToolChain(), C.getArgs(), Inputs);
Chad Rosierbe10f982011-08-02 17:58:04 +00001266
Chad Rosier4f81fc22011-08-12 23:30:05 +00001267 for (InputList::iterator it = Inputs.begin(), ie = Inputs.end(); it != ie;) {
Chad Rosierd57133d2011-08-18 00:22:25 +00001268 bool IgnoreInput = false;
1269
1270 // Ignore input from stdin or any inputs that cannot be preprocessed.
Paul Robinsonf44157d2014-04-28 22:24:44 +00001271 // Check type first as not all linker inputs have a value.
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001272 if (types::getPreprocessedType(it->first) == types::TY_INVALID) {
Paul Robinsonf44157d2014-04-28 22:24:44 +00001273 IgnoreInput = true;
1274 } else if (!strcmp(it->second->getValue(), "-")) {
Chad Rosierd57133d2011-08-18 00:22:25 +00001275 Diag(clang::diag::note_drv_command_failed_diag_msg)
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001276 << "Error generating preprocessed source(s) - "
1277 "ignoring input from stdin.";
Chad Rosierd57133d2011-08-18 00:22:25 +00001278 IgnoreInput = true;
Chad Rosierd57133d2011-08-18 00:22:25 +00001279 }
1280
1281 if (IgnoreInput) {
Chad Rosier4f81fc22011-08-12 23:30:05 +00001282 it = Inputs.erase(it);
1283 ie = Inputs.end();
Chad Rosier6fdf38b2011-08-17 23:08:45 +00001284 } else {
Chad Rosier4f81fc22011-08-12 23:30:05 +00001285 ++it;
Chad Rosier6fdf38b2011-08-17 23:08:45 +00001286 }
Chad Rosier4f81fc22011-08-12 23:30:05 +00001287 }
Chad Rosierd57133d2011-08-18 00:22:25 +00001288
Chad Rosierc5103c32013-01-29 23:57:10 +00001289 if (Inputs.empty()) {
1290 Diag(clang::diag::note_drv_command_failed_diag_msg)
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001291 << "Error generating preprocessed source(s) - "
1292 "no preprocessable inputs.";
Chad Rosierc5103c32013-01-29 23:57:10 +00001293 return;
1294 }
1295
Chad Rosiere75ef402011-09-06 23:52:36 +00001296 // Don't attempt to generate preprocessed files if multiple -arch options are
Chad Rosier636d2832012-02-13 18:16:28 +00001297 // used, unless they're all duplicates.
1298 llvm::StringSet<> ArchNames;
Saleem Abdulrasool688b6bc2014-12-29 19:01:36 +00001299 for (const Arg *A : C.getArgs()) {
Chad Rosiere75ef402011-09-06 23:52:36 +00001300 if (A->getOption().matches(options::OPT_arch)) {
Richard Smithbd55daf2012-11-01 04:30:05 +00001301 StringRef ArchName = A->getValue();
Chad Rosier636d2832012-02-13 18:16:28 +00001302 ArchNames.insert(ArchName);
Chad Rosiere75ef402011-09-06 23:52:36 +00001303 }
1304 }
Chad Rosier636d2832012-02-13 18:16:28 +00001305 if (ArchNames.size() > 1) {
1306 Diag(clang::diag::note_drv_command_failed_diag_msg)
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001307 << "Error generating preprocessed source(s) - cannot generate "
1308 "preprocessed source with multiple -arch options.";
Chad Rosier636d2832012-02-13 18:16:28 +00001309 return;
1310 }
Chad Rosiere75ef402011-09-06 23:52:36 +00001311
Chandler Carruth7f1417f2012-01-24 10:43:44 +00001312 // Construct the list of abstract actions to perform for this compilation. On
1313 // Darwin OSes this uses the driver-driver and builds universal actions.
Chandler Carruthcb916192012-01-25 08:49:21 +00001314 const ToolChain &TC = C.getDefaultToolChain();
Tim Northover157d9112014-01-16 08:48:16 +00001315 if (TC.getTriple().isOSBinFormatMachO())
Artem Belevich5e2a3ec2015-11-17 22:28:40 +00001316 BuildUniversalActions(C, TC, Inputs);
Chad Rosierbe10f982011-08-02 17:58:04 +00001317 else
Justin Lebar0f3474c2016-02-11 02:00:50 +00001318 BuildActions(C, C.getArgs(), Inputs, C.getActions());
Chad Rosierbe10f982011-08-02 17:58:04 +00001319
1320 BuildJobs(C);
1321
1322 // If there were errors building the compilation, quit now.
Richard Smith5bb4cdf2012-12-20 02:22:15 +00001323 if (Trap.hasErrorOccurred()) {
Chad Rosierbe10f982011-08-02 17:58:04 +00001324 Diag(clang::diag::note_drv_command_failed_diag_msg)
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001325 << "Error generating preprocessed source(s).";
Chad Rosierbe10f982011-08-02 17:58:04 +00001326 return;
1327 }
1328
1329 // Generate preprocessed output.
Chad Rosierdd60e092013-01-29 20:15:05 +00001330 SmallVector<std::pair<int, const Command *>, 4> FailingCommands;
Justin Bogner0cd92482015-07-02 22:52:08 +00001331 C.ExecuteJobs(C.getJobs(), FailingCommands);
Chad Rosierbe10f982011-08-02 17:58:04 +00001332
Justin Bognerbc89b182014-10-20 21:20:27 +00001333 // If any of the preprocessing commands failed, clean up and exit.
1334 if (!FailingCommands.empty()) {
Chad Rosierbe10f982011-08-02 17:58:04 +00001335 Diag(clang::diag::note_drv_command_failed_diag_msg)
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001336 << "Error generating preprocessed source(s).";
Justin Bognerbc89b182014-10-20 21:20:27 +00001337 return;
Chad Rosierbe10f982011-08-02 17:58:04 +00001338 }
Justin Bognerbc89b182014-10-20 21:20:27 +00001339
Justin Bognerc1fdf7f2014-10-20 21:47:56 +00001340 const ArgStringList &TempFiles = C.getTempFiles();
1341 if (TempFiles.empty()) {
1342 Diag(clang::diag::note_drv_command_failed_diag_msg)
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001343 << "Error generating preprocessed source(s).";
Justin Bognerc1fdf7f2014-10-20 21:47:56 +00001344 return;
1345 }
1346
Justin Bognerbc89b182014-10-20 21:20:27 +00001347 Diag(clang::diag::note_drv_command_failed_diag_msg)
1348 << "\n********************\n\n"
1349 "PLEASE ATTACH THE FOLLOWING FILES TO THE BUG REPORT:\n"
1350 "Preprocessed source(s) and associated run script(s) are located at:";
Justin Bognerbc89b182014-10-20 21:20:27 +00001351
Justin Bogner659ecc32014-10-20 22:47:23 +00001352 SmallString<128> VFS;
Bruno Cardoso Lopes02681c42016-11-17 21:41:22 +00001353 SmallString<128> ReproCrashFilename;
Justin Bogner659ecc32014-10-20 22:47:23 +00001354 for (const char *TempFile : TempFiles) {
Justin Bognerc1fdf7f2014-10-20 21:47:56 +00001355 Diag(clang::diag::note_drv_command_failed_diag_msg) << TempFile;
Alex Lorenz045c5142018-04-07 00:03:27 +00001356 if (Report)
1357 Report->TemporaryFiles.push_back(TempFile);
Bruno Cardoso Lopes02681c42016-11-17 21:41:22 +00001358 if (ReproCrashFilename.empty()) {
1359 ReproCrashFilename = TempFile;
1360 llvm::sys::path::replace_extension(ReproCrashFilename, ".crash");
1361 }
Justin Bogner659ecc32014-10-20 22:47:23 +00001362 if (StringRef(TempFile).endswith(".cache")) {
1363 // In some cases (modules) we'll dump extra data to help with reproducing
1364 // the crash into a directory next to the output.
1365 VFS = llvm::sys::path::filename(TempFile);
1366 llvm::sys::path::append(VFS, "vfs", "vfs.yaml");
1367 }
1368 }
Justin Bognerc1fdf7f2014-10-20 21:47:56 +00001369
1370 // Assume associated files are based off of the first temporary file.
Justin Bogner25645152014-10-21 17:24:44 +00001371 CrashReportInfo CrashInfo(TempFiles[0], VFS);
Justin Bognerc1fdf7f2014-10-20 21:47:56 +00001372
Bob Haarman7e4d3ff2018-07-09 21:07:20 +00001373 llvm::SmallString<128> Script(CrashInfo.Filename);
1374 llvm::sys::path::replace_extension(Script, "sh");
Justin Bognerc1fdf7f2014-10-20 21:47:56 +00001375 std::error_code EC;
Zachary Turner1f67a3c2018-06-07 19:58:58 +00001376 llvm::raw_fd_ostream ScriptOS(Script, EC, llvm::sys::fs::CD_CreateNew);
Justin Bognerc1fdf7f2014-10-20 21:47:56 +00001377 if (EC) {
1378 Diag(clang::diag::note_drv_command_failed_diag_msg)
Bob Haarman7e4d3ff2018-07-09 21:07:20 +00001379 << "Error generating run script: " << Script << " " << EC.message();
Justin Bognerc1fdf7f2014-10-20 21:47:56 +00001380 } else {
Justin Bogner42220ed2015-03-12 00:14:35 +00001381 ScriptOS << "# Crash reproducer for " << getClangFullVersion() << "\n"
Justin Bognered9cbe02015-07-09 06:58:31 +00001382 << "# Driver args: ";
1383 printArgList(ScriptOS, C.getInputArgs());
1384 ScriptOS << "# Original command: ";
Justin Bogner42220ed2015-03-12 00:14:35 +00001385 Cmd.Print(ScriptOS, "\n", /*Quote=*/true);
Justin Bogner33bdbc62014-10-21 18:03:08 +00001386 Cmd.Print(ScriptOS, "\n", /*Quote=*/true, &CrashInfo);
Alex Lorenz045c5142018-04-07 00:03:27 +00001387 if (!AdditionalInformation.empty())
1388 ScriptOS << "\n# Additional information: " << AdditionalInformation
1389 << "\n";
1390 if (Report)
Bob Haarman7e4d3ff2018-07-09 21:07:20 +00001391 Report->TemporaryFiles.push_back(Script.str());
Justin Bognerc1fdf7f2014-10-20 21:47:56 +00001392 Diag(clang::diag::note_drv_command_failed_diag_msg) << Script;
Justin Bognerbc89b182014-10-20 21:20:27 +00001393 }
Saleem Abdulrasool3661a822015-01-12 02:33:09 +00001394
Bruno Cardoso Lopes02681c42016-11-17 21:41:22 +00001395 // On darwin, provide information about the .crash diagnostic report.
1396 if (llvm::Triple(llvm::sys::getProcessTriple()).isOSDarwin()) {
1397 SmallString<128> CrashDiagDir;
1398 if (getCrashDiagnosticFile(ReproCrashFilename, CrashDiagDir)) {
1399 Diag(clang::diag::note_drv_command_failed_diag_msg)
1400 << ReproCrashFilename.str();
1401 } else { // Suggest a directory for the user to look for .crash files.
1402 llvm::sys::path::append(CrashDiagDir, Name);
1403 CrashDiagDir += "_<YYYY-MM-DD-HHMMSS>_<hostname>.crash";
1404 Diag(clang::diag::note_drv_command_failed_diag_msg)
1405 << "Crash backtrace is located in";
1406 Diag(clang::diag::note_drv_command_failed_diag_msg)
1407 << CrashDiagDir.str();
1408 Diag(clang::diag::note_drv_command_failed_diag_msg)
1409 << "(choose the .crash file that corresponds to your crash)";
1410 }
1411 }
1412
Saleem Abdulrasool3661a822015-01-12 02:33:09 +00001413 for (const auto &A : C.getArgs().filtered(options::OPT_frewrite_map_file,
1414 options::OPT_frewrite_map_file_EQ))
1415 Diag(clang::diag::note_drv_command_failed_diag_msg) << A->getValue();
1416
Justin Bognerbc89b182014-10-20 21:20:27 +00001417 Diag(clang::diag::note_drv_command_failed_diag_msg)
1418 << "\n\n********************";
Chad Rosierbe10f982011-08-02 17:58:04 +00001419}
1420
Justin Bogner0cd92482015-07-02 22:52:08 +00001421void Driver::setUpResponseFiles(Compilation &C, Command &Cmd) {
Simon Atanasyan27c0f202019-04-02 18:03:15 +00001422 // Since commandLineFitsWithinSystemLimits() may underestimate system's
1423 // capacity if the tool does not support response files, there is a chance/
1424 // that things will just work without a response file, so we silently just
1425 // skip it.
Justin Bogner0cd92482015-07-02 22:52:08 +00001426 if (Cmd.getCreator().getResponseFilesSupport() == Tool::RF_None ||
Simon Atanasyan27c0f202019-04-02 18:03:15 +00001427 llvm::sys::commandLineFitsWithinSystemLimits(Cmd.getExecutable(),
1428 Cmd.getArguments()))
Reid Kleckner0290c9c2014-09-15 17:45:39 +00001429 return;
1430
1431 std::string TmpName = GetTemporaryPath("response", "txt");
Malcolm Parsonsf76f6502016-11-02 10:39:27 +00001432 Cmd.setResponseFile(C.addTempFile(C.getArgs().MakeArgString(TmpName)));
Reid Kleckner0290c9c2014-09-15 17:45:39 +00001433}
1434
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001435int Driver::ExecuteCompilation(
1436 Compilation &C,
1437 SmallVectorImpl<std::pair<int, const Command *>> &FailingCommands) {
Daniel Dunbar38bfda62009-07-01 20:03:04 +00001438 // Just print if -### was present.
1439 if (C.getArgs().hasArg(options::OPT__HASH_HASH_HASH)) {
Hans Wennborgb212b342013-09-12 18:23:34 +00001440 C.getJobs().Print(llvm::errs(), "\n", true);
Daniel Dunbar38bfda62009-07-01 20:03:04 +00001441 return 0;
1442 }
1443
1444 // If there were errors building the compilation, quit now.
Chad Rosierbe10f982011-08-02 17:58:04 +00001445 if (Diags.hasErrorOccurred())
Daniel Dunbar38bfda62009-07-01 20:03:04 +00001446 return 1;
1447
Reid Kleckner0290c9c2014-09-15 17:45:39 +00001448 // Set up response file names for each command, if necessary
Justin Bogner0cd92482015-07-02 22:52:08 +00001449 for (auto &Job : C.getJobs())
1450 setUpResponseFiles(C, Job);
Reid Kleckner0290c9c2014-09-15 17:45:39 +00001451
Justin Bogner0cd92482015-07-02 22:52:08 +00001452 C.ExecuteJobs(C.getJobs(), FailingCommands);
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001453
Daniel Dunbar07494792010-05-22 00:37:20 +00001454 // If the command succeeded, we are done.
Chad Rosierdd60e092013-01-29 20:15:05 +00001455 if (FailingCommands.empty())
1456 return 0;
Daniel Dunbar07494792010-05-22 00:37:20 +00001457
Chad Rosierdd60e092013-01-29 20:15:05 +00001458 // Otherwise, remove result files and print extra information about abnormal
1459 // failures.
Nick Desaulniers9d0df312018-10-15 17:39:00 +00001460 int Res = 0;
Douglas Katzman6bbffc42015-06-25 18:51:37 +00001461 for (const auto &CmdPair : FailingCommands) {
Nick Desaulniers9d0df312018-10-15 17:39:00 +00001462 int CommandRes = CmdPair.first;
Douglas Katzman6bbffc42015-06-25 18:51:37 +00001463 const Command *FailingCommand = CmdPair.second;
Daniel Dunbar38bfda62009-07-01 20:03:04 +00001464
Chad Rosierdd60e092013-01-29 20:15:05 +00001465 // Remove result files if we're not saving temps.
Reid Kleckner68eb60b2015-02-02 22:41:48 +00001466 if (!isSaveTempsEnabled()) {
Chad Rosierdd60e092013-01-29 20:15:05 +00001467 const JobAction *JA = cast<JobAction>(&FailingCommand->getSource());
1468 C.CleanupFileMap(C.getResultFiles(), JA, true);
1469
1470 // Failure result files are valid unless we crashed.
Nick Desaulniers9d0df312018-10-15 17:39:00 +00001471 if (CommandRes < 0)
Chad Rosierdd60e092013-01-29 20:15:05 +00001472 C.CleanupFileMap(C.getFailureResultFiles(), JA, true);
1473 }
1474
Nick Desaulniers9d0df312018-10-15 17:39:00 +00001475#if LLVM_ON_UNIX
1476 // llvm/lib/Support/Unix/Signals.inc will exit with a special return code
1477 // for SIGPIPE. Do not print diagnostics for this case.
1478 if (CommandRes == EX_IOERR) {
1479 Res = CommandRes;
1480 continue;
1481 }
1482#endif
1483
Chad Rosierdd60e092013-01-29 20:15:05 +00001484 // Print extra information about abnormal failures, if possible.
1485 //
1486 // This is ad-hoc, but we don't want to be excessively noisy. If the result
Justin Bogner5aaf2e72014-06-26 20:59:36 +00001487 // status was 1, assume the command failed normally. In particular, if it
Chad Rosierdd60e092013-01-29 20:15:05 +00001488 // was the compiler then assume it gave a reasonable error code. Failures
1489 // in other tools are less common, and they generally have worse
1490 // diagnostics, so always print the diagnostic there.
1491 const Tool &FailingTool = FailingCommand->getCreator();
1492
Nick Desaulniers9d0df312018-10-15 17:39:00 +00001493 if (!FailingCommand->getCreator().hasGoodDiagnostics() || CommandRes != 1) {
Chad Rosierdd60e092013-01-29 20:15:05 +00001494 // FIXME: See FIXME above regarding result code interpretation.
Nick Desaulniers9d0df312018-10-15 17:39:00 +00001495 if (CommandRes < 0)
Chad Rosierdd60e092013-01-29 20:15:05 +00001496 Diag(clang::diag::err_drv_command_signalled)
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001497 << FailingTool.getShortName();
Chad Rosierdd60e092013-01-29 20:15:05 +00001498 else
Nick Desaulniers9d0df312018-10-15 17:39:00 +00001499 Diag(clang::diag::err_drv_command_failed)
1500 << FailingTool.getShortName() << CommandRes;
Chad Rosierdd60e092013-01-29 20:15:05 +00001501 }
Peter Collingbourne119cfaa2011-11-21 00:01:05 +00001502 }
Nick Desaulniers9d0df312018-10-15 17:39:00 +00001503 return Res;
Daniel Dunbar38bfda62009-07-01 20:03:04 +00001504}
1505
Daniel Dunbara7b5e212009-04-15 16:34:29 +00001506void Driver::PrintHelp(bool ShowHidden) const {
Hans Wennborg6ddc6902013-07-27 00:23:45 +00001507 unsigned IncludedFlagsBitmask;
1508 unsigned ExcludedFlagsBitmask;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00001509 std::tie(IncludedFlagsBitmask, ExcludedFlagsBitmask) =
Hans Wennborg797004d2018-11-08 11:27:04 +00001510 getIncludeExcludeOptionFlagMasks(IsCLMode());
Hans Wennborg6ddc6902013-07-27 00:23:45 +00001511
1512 ExcludedFlagsBitmask |= options::NoDriverOption;
1513 if (!ShowHidden)
1514 ExcludedFlagsBitmask |= HelpHidden;
1515
Fangrui Songd0028232018-10-10 00:15:33 +00001516 std::string Usage = llvm::formatv("{0} [options] file...", Name).str();
1517 getOpts().PrintHelp(llvm::outs(), Usage.c_str(), DriverTitle.c_str(),
George Rimar5dbfa4e2017-07-26 09:10:17 +00001518 IncludedFlagsBitmask, ExcludedFlagsBitmask,
1519 /*ShowAllAliases=*/false);
Daniel Dunbar7c925282009-03-31 21:38:17 +00001520}
1521
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001522void Driver::PrintVersion(const Compilation &C, raw_ostream &OS) const {
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001523 // FIXME: The following handlers should use a callback mechanism, we don't
1524 // know what the client would like to do.
Ted Kremenek4c0df3d2010-01-23 02:11:34 +00001525 OS << getClangFullVersion() << '\n';
Daniel Dunbarb10248802009-03-26 16:09:13 +00001526 const ToolChain &TC = C.getDefaultToolChain();
Daniel Dunbar08e41d62009-07-21 20:06:58 +00001527 OS << "Target: " << TC.getTripleString() << '\n';
Daniel Dunbar10978e42009-06-16 23:32:58 +00001528
1529 // Print the threading model.
Jonathan Roelofsb140a102014-10-03 21:57:44 +00001530 if (Arg *A = C.getArgs().getLastArg(options::OPT_mthread_model)) {
1531 // Don't print if the ToolChain would have barfed on it already
1532 if (TC.isThreadModelSupported(A->getValue()))
1533 OS << "Thread model: " << A->getValue();
1534 } else
Thomas Livelyf3b4f992019-02-28 18:39:08 +00001535 OS << "Thread model: " << TC.getThreadModel();
Jonathan Roelofsb140a102014-10-03 21:57:44 +00001536 OS << '\n';
Chandler Carruth9ade6a92015-08-05 17:07:33 +00001537
1538 // Print out the install directory.
1539 OS << "InstalledDir: " << InstalledDir << '\n';
Serge Pavlov208ac652018-01-01 13:27:01 +00001540
1541 // If configuration file was used, print its path.
1542 if (!ConfigFile.empty())
1543 OS << "Configuration file: " << ConfigFile << '\n';
Daniel Dunbar5e0f6af2009-03-13 00:51:18 +00001544}
1545
Chris Lattner86ed5b02010-05-05 05:53:24 +00001546/// PrintDiagnosticCategories - Implement the --print-diagnostic-categories
1547/// option.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001548static void PrintDiagnosticCategories(raw_ostream &OS) {
Argyrios Kyrtzidis0e37afa2011-05-25 05:05:01 +00001549 // Skip the empty category.
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001550 for (unsigned i = 1, max = DiagnosticIDs::getNumberOfCategories(); i != max;
1551 ++i)
Argyrios Kyrtzidis0e37afa2011-05-25 05:05:01 +00001552 OS << i << ',' << DiagnosticIDs::getCategoryNameFromID(i) << '\n';
Chris Lattner86ed5b02010-05-05 05:53:24 +00001553}
1554
Yuka Takahashi41789e42018-03-05 08:54:20 +00001555void Driver::HandleAutocompletions(StringRef PassedFlags) const {
Yuka Takahashi503da8f2018-03-05 09:01:31 +00001556 if (PassedFlags == "")
1557 return;
Yuka Takahashi1a895202017-08-29 17:46:46 +00001558 // Print out all options that start with a given argument. This is used for
1559 // shell autocompletion.
1560 std::vector<std::string> SuggestedCompletions;
Yuka Takahashi41789e42018-03-05 08:54:20 +00001561 std::vector<std::string> Flags;
Yuka Takahashi1a895202017-08-29 17:46:46 +00001562
1563 unsigned short DisableFlags =
1564 options::NoDriverOption | options::Unsupported | options::Ignored;
Yuka Takahashi41789e42018-03-05 08:54:20 +00001565
Yuka Takahashi46106f52018-10-24 12:43:25 +00001566 // Distinguish "--autocomplete=-someflag" and "--autocomplete=-someflag,"
1567 // because the latter indicates that the user put space before pushing tab
1568 // which should end up in a file completion.
1569 const bool HasSpace = PassedFlags.endswith(",");
1570
Yuka Takahashi41789e42018-03-05 08:54:20 +00001571 // Parse PassedFlags by "," as all the command-line flags are passed to this
1572 // function separated by ","
1573 StringRef TargetFlags = PassedFlags;
1574 while (TargetFlags != "") {
1575 StringRef CurFlag;
1576 std::tie(CurFlag, TargetFlags) = TargetFlags.split(",");
1577 Flags.push_back(std::string(CurFlag));
Yuka Takahashi1a895202017-08-29 17:46:46 +00001578 }
1579
Yuka Takahashi41789e42018-03-05 08:54:20 +00001580 // We want to show cc1-only options only when clang is invoked with -cc1 or
1581 // -Xclang.
Fangrui Song9ac13a12019-02-10 05:54:57 +00001582 if (llvm::is_contained(Flags, "-Xclang") || llvm::is_contained(Flags, "-cc1"))
Yuka Takahashi41789e42018-03-05 08:54:20 +00001583 DisableFlags &= ~options::NoDriverOption;
1584
1585 StringRef Cur;
1586 Cur = Flags.at(Flags.size() - 1);
1587 StringRef Prev;
1588 if (Flags.size() >= 2) {
1589 Prev = Flags.at(Flags.size() - 2);
1590 SuggestedCompletions = Opts->suggestValueCompletions(Prev, Cur);
1591 }
1592
1593 if (SuggestedCompletions.empty())
1594 SuggestedCompletions = Opts->suggestValueCompletions(Cur, "");
1595
Yuka Takahashi46106f52018-10-24 12:43:25 +00001596 // If Flags were empty, it means the user typed `clang [tab]` where we should
1597 // list all possible flags. If there was no value completion and the user
1598 // pressed tab after a space, we should fall back to a file completion.
1599 // We're printing a newline to be consistent with what we print at the end of
1600 // this function.
1601 if (SuggestedCompletions.empty() && HasSpace && !Flags.empty()) {
1602 llvm::outs() << '\n';
1603 return;
1604 }
1605
Yuka Takahashidf9c7e32018-10-24 08:24:16 +00001606 // When flag ends with '=' and there was no value completion, return empty
1607 // string and fall back to the file autocompletion.
1608 if (SuggestedCompletions.empty() && !Cur.endswith("=")) {
Yuka Takahashi1a895202017-08-29 17:46:46 +00001609 // If the flag is in the form of "--autocomplete=-foo",
1610 // we were requested to print out all option names that start with "-foo".
1611 // For example, "--autocomplete=-fsyn" is expanded to "-fsyntax-only".
Yuka Takahashi41789e42018-03-05 08:54:20 +00001612 SuggestedCompletions = Opts->findByPrefix(Cur, DisableFlags);
Yuka Takahashi1a895202017-08-29 17:46:46 +00001613
1614 // We have to query the -W flags manually as they're not in the OptTable.
1615 // TODO: Find a good way to add them to OptTable instead and them remove
1616 // this code.
1617 for (StringRef S : DiagnosticIDs::getDiagnosticFlags())
Yuka Takahashi41789e42018-03-05 08:54:20 +00001618 if (S.startswith(Cur))
Yuka Takahashi1a895202017-08-29 17:46:46 +00001619 SuggestedCompletions.push_back(S);
Yuka Takahashi1a895202017-08-29 17:46:46 +00001620 }
1621
1622 // Sort the autocomplete candidates so that shells print them out in a
1623 // deterministic order. We could sort in any way, but we chose
1624 // case-insensitive sorting for consistency with the -help option
1625 // which prints out options in the case-insensitive alphabetical order.
Fangrui Song55fab262018-09-26 22:16:28 +00001626 llvm::sort(SuggestedCompletions, [](StringRef A, StringRef B) {
1627 if (int X = A.compare_lower(B))
1628 return X < 0;
1629 return A.compare(B) > 0;
1630 });
Yuka Takahashi1a895202017-08-29 17:46:46 +00001631
1632 llvm::outs() << llvm::join(SuggestedCompletions, "\n") << '\n';
1633}
1634
Daniel Dunbarf0eddb82009-03-18 02:55:38 +00001635bool Driver::HandleImmediateArgs(const Compilation &C) {
Daniel Dunbar18974bd2010-06-11 22:00:19 +00001636 // The order these options are handled in gcc is all over the place, but we
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001637 // don't expect inconsistencies w.r.t. that to matter in practice.
Daniel Dunbar7c925282009-03-31 21:38:17 +00001638
Daniel Dunbar1b09e042010-09-17 02:47:28 +00001639 if (C.getArgs().hasArg(options::OPT_dumpmachine)) {
1640 llvm::outs() << C.getDefaultToolChain().getTripleString() << '\n';
1641 return false;
1642 }
1643
Daniel Dunbara9bbcfa2009-04-04 05:17:38 +00001644 if (C.getArgs().hasArg(options::OPT_dumpversion)) {
Daniel Dunbare26e5002011-01-12 00:43:47 +00001645 // Since -dumpversion is only implemented for pedantic GCC compatibility, we
1646 // return an answer which matches our definition of __VERSION__.
Sylvestre Ledrua199a9b2019-03-25 18:06:20 +00001647 llvm::outs() << CLANG_VERSION_STRING << "\n";
Daniel Dunbara9bbcfa2009-04-04 05:17:38 +00001648 return false;
1649 }
Daniel Dunbarfb3d7472010-06-14 21:23:12 +00001650
Chris Lattner86ed5b02010-05-05 05:53:24 +00001651 if (C.getArgs().hasArg(options::OPT__print_diagnostic_categories)) {
1652 PrintDiagnosticCategories(llvm::outs());
1653 return false;
1654 }
Daniel Dunbara9bbcfa2009-04-04 05:17:38 +00001655
James Molloya3c85b82012-05-01 14:57:16 +00001656 if (C.getArgs().hasArg(options::OPT_help) ||
Daniel Dunbara7b5e212009-04-15 16:34:29 +00001657 C.getArgs().hasArg(options::OPT__help_hidden)) {
1658 PrintHelp(C.getArgs().hasArg(options::OPT__help_hidden));
Daniel Dunbar7c925282009-03-31 21:38:17 +00001659 return false;
1660 }
1661
Daniel Dunbarb0006ae2009-04-02 15:05:41 +00001662 if (C.getArgs().hasArg(options::OPT__version)) {
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001663 // Follow gcc behavior and use stdout for --version and stderr for -v.
Daniel Dunbar08e41d62009-07-21 20:06:58 +00001664 PrintVersion(C, llvm::outs());
Daniel Dunbarb0006ae2009-04-02 15:05:41 +00001665 return false;
1666 }
1667
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001668 if (C.getArgs().hasArg(options::OPT_v) ||
Daniel Dunbarf0eddb82009-03-18 02:55:38 +00001669 C.getArgs().hasArg(options::OPT__HASH_HASH_HASH)) {
Daniel Dunbar08e41d62009-07-21 20:06:58 +00001670 PrintVersion(C, llvm::errs());
Daniel Dunbar5e0f6af2009-03-13 00:51:18 +00001671 SuppressMissingInputWarning = true;
1672 }
1673
Serge Pavlov208ac652018-01-01 13:27:01 +00001674 if (C.getArgs().hasArg(options::OPT_v)) {
1675 if (!SystemConfigDir.empty())
1676 llvm::errs() << "System configuration file directory: "
1677 << SystemConfigDir << "\n";
1678 if (!UserConfigDir.empty())
1679 llvm::errs() << "User configuration file directory: "
1680 << UserConfigDir << "\n";
1681 }
1682
Daniel Dunbarf0eddb82009-03-18 02:55:38 +00001683 const ToolChain &TC = C.getDefaultToolChain();
Chandler Carruth0ae39aa2013-07-30 17:57:09 +00001684
1685 if (C.getArgs().hasArg(options::OPT_v))
1686 TC.printVerboseInfo(llvm::errs());
1687
Meador Inge51208a32017-04-04 21:46:50 +00001688 if (C.getArgs().hasArg(options::OPT_print_resource_dir)) {
Meador Ingea9113952017-04-05 22:27:20 +00001689 llvm::outs() << ResourceDir << '\n';
Meador Inge51208a32017-04-04 21:46:50 +00001690 return false;
1691 }
1692
Daniel Dunbard972e222009-03-20 04:37:21 +00001693 if (C.getArgs().hasArg(options::OPT_print_search_dirs)) {
1694 llvm::outs() << "programs: =";
Douglas Katzman51fe7bf2015-06-23 22:43:50 +00001695 bool separator = false;
1696 for (const std::string &Path : TC.getProgramPaths()) {
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001697 if (separator)
Martin Storsjoceb71e82019-04-25 20:03:20 +00001698 llvm::outs() << llvm::sys::EnvPathSeparator;
Douglas Katzman51fe7bf2015-06-23 22:43:50 +00001699 llvm::outs() << Path;
1700 separator = true;
Daniel Dunbard972e222009-03-20 04:37:21 +00001701 }
1702 llvm::outs() << "\n";
Peter Collingbournefa9771f2011-09-06 02:08:31 +00001703 llvm::outs() << "libraries: =" << ResourceDir;
Joerg Sonnenberger9c3e69b2011-07-16 10:50:05 +00001704
Sebastian Pop980920a2012-04-16 04:16:43 +00001705 StringRef sysroot = C.getSysRoot();
Joerg Sonnenberger9c3e69b2011-07-16 10:50:05 +00001706
Douglas Katzman51fe7bf2015-06-23 22:43:50 +00001707 for (const std::string &Path : TC.getFilePaths()) {
1708 // Always print a separator. ResourceDir was the first item shown.
Martin Storsjoceb71e82019-04-25 20:03:20 +00001709 llvm::outs() << llvm::sys::EnvPathSeparator;
Douglas Katzman51fe7bf2015-06-23 22:43:50 +00001710 // Interpretation of leading '=' is needed only for NetBSD.
1711 if (Path[0] == '=')
Douglas Katzman26eabf62015-06-24 15:10:30 +00001712 llvm::outs() << sysroot << Path.substr(1);
Joerg Sonnenberger9c3e69b2011-07-16 10:50:05 +00001713 else
Douglas Katzman51fe7bf2015-06-23 22:43:50 +00001714 llvm::outs() << Path;
Daniel Dunbard972e222009-03-20 04:37:21 +00001715 }
1716 llvm::outs() << "\n";
Daniel Dunbar7c925282009-03-31 21:38:17 +00001717 return false;
Daniel Dunbard972e222009-03-20 04:37:21 +00001718 }
1719
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001720 // FIXME: The following handlers should use a callback mechanism, we don't
1721 // know what the client would like to do.
Daniel Dunbarf0eddb82009-03-18 02:55:38 +00001722 if (Arg *A = C.getArgs().getLastArg(options::OPT_print_file_name_EQ)) {
Richard Smithbd55daf2012-11-01 04:30:05 +00001723 llvm::outs() << GetFilePath(A->getValue(), TC) << "\n";
Daniel Dunbar5e0f6af2009-03-13 00:51:18 +00001724 return false;
1725 }
1726
Daniel Dunbarf0eddb82009-03-18 02:55:38 +00001727 if (Arg *A = C.getArgs().getLastArg(options::OPT_print_prog_name_EQ)) {
Saleem Abdulrasoole5f3cf82018-05-01 18:40:42 +00001728 StringRef ProgName = A->getValue();
1729
1730 // Null program name cannot have a path.
1731 if (! ProgName.empty())
1732 llvm::outs() << GetProgramPath(ProgName, TC);
1733
1734 llvm::outs() << "\n";
Daniel Dunbar5e0f6af2009-03-13 00:51:18 +00001735 return false;
1736 }
1737
Yuka Takahashic8068db2017-05-23 18:39:08 +00001738 if (Arg *A = C.getArgs().getLastArg(options::OPT_autocomplete)) {
Yuka Takahashiba5d4af2017-06-20 16:31:31 +00001739 StringRef PassedFlags = A->getValue();
Yuka Takahashi41789e42018-03-05 08:54:20 +00001740 HandleAutocompletions(PassedFlags);
Yuka Takahashic8068db2017-05-23 18:39:08 +00001741 return false;
1742 }
1743
Daniel Dunbarf0eddb82009-03-18 02:55:38 +00001744 if (C.getArgs().hasArg(options::OPT_print_libgcc_file_name)) {
Michal Gorny7cfe4802016-10-10 12:23:40 +00001745 ToolChain::RuntimeLibType RLT = TC.GetRuntimeLibType(C.getArgs());
Leo Li23bb21c2017-08-24 01:51:51 +00001746 const llvm::Triple Triple(TC.ComputeEffectiveClangTriple(C.getArgs()));
1747 RegisterEffectiveTriple TripleRAII(TC, Triple);
Michal Gorny7cfe4802016-10-10 12:23:40 +00001748 switch (RLT) {
1749 case ToolChain::RLT_CompilerRT:
1750 llvm::outs() << TC.getCompilerRT(C.getArgs(), "builtins") << "\n";
1751 break;
1752 case ToolChain::RLT_Libgcc:
1753 llvm::outs() << GetFilePath("libgcc.a", TC) << "\n";
1754 break;
1755 }
Daniel Dunbar5e0f6af2009-03-13 00:51:18 +00001756 return false;
1757 }
1758
Daniel Dunbar1b3ec3a2009-06-16 23:25:22 +00001759 if (C.getArgs().hasArg(options::OPT_print_multi_lib)) {
Douglas Katzmana34b7bf2015-06-30 19:32:57 +00001760 for (const Multilib &Multilib : TC.getMultilibs())
1761 llvm::outs() << Multilib << "\n";
Daniel Dunbar1b3ec3a2009-06-16 23:25:22 +00001762 return false;
1763 }
1764
Jonathan Roelofs2cea1be2014-02-12 03:21:20 +00001765 if (C.getArgs().hasArg(options::OPT_print_multi_directory)) {
Christian Bruel6ccc4a72018-09-06 14:03:44 +00001766 const Multilib &Multilib = TC.getMultilib();
1767 if (Multilib.gccSuffix().empty())
1768 llvm::outs() << ".\n";
1769 else {
1770 StringRef Suffix(Multilib.gccSuffix());
1771 assert(Suffix.front() == '/');
1772 llvm::outs() << Suffix.substr(1) << "\n";
Jonathan Roelofs3fa96d82014-02-12 01:36:51 +00001773 }
Jonathan Roelofs0e7ec602014-02-12 01:29:25 +00001774 return false;
1775 }
Petr Hosekbc86a992018-08-16 00:22:03 +00001776
1777 if (C.getArgs().hasArg(options::OPT_print_target_triple)) {
1778 llvm::outs() << TC.getTripleString() << "\n";
1779 return false;
1780 }
1781
1782 if (C.getArgs().hasArg(options::OPT_print_effective_triple)) {
1783 const llvm::Triple Triple(TC.ComputeEffectiveClangTriple(C.getArgs()));
1784 llvm::outs() << Triple.getTriple() << "\n";
1785 return false;
1786 }
1787
Daniel Dunbar5e0f6af2009-03-13 00:51:18 +00001788 return true;
1789}
1790
Douglas Katzmanfd528672015-06-11 15:05:22 +00001791// Display an action graph human-readably. Action A is the "sink" node
1792// and latest-occuring action. Traversal is in pre-order, visiting the
1793// inputs to each action before printing the action itself.
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001794static unsigned PrintActions1(const Compilation &C, Action *A,
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001795 std::map<Action *, unsigned> &Ids) {
Douglas Katzmanfd528672015-06-11 15:05:22 +00001796 if (Ids.count(A)) // A was already visited.
Daniel Dunbaraaf1ea62009-03-13 12:19:02 +00001797 return Ids[A];
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001798
Daniel Dunbaraaf1ea62009-03-13 12:19:02 +00001799 std::string str;
1800 llvm::raw_string_ostream os(str);
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001801
Daniel Dunbaraaf1ea62009-03-13 12:19:02 +00001802 os << Action::getClassName(A->getKind()) << ", ";
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001803 if (InputAction *IA = dyn_cast<InputAction>(A)) {
Richard Smithbd55daf2012-11-01 04:30:05 +00001804 os << "\"" << IA->getInputArg().getValue() << "\"";
Daniel Dunbaraaf1ea62009-03-13 12:19:02 +00001805 } else if (BindArchAction *BIA = dyn_cast<BindArchAction>(A)) {
Douglas Katzmanb7e8ef02015-06-25 19:37:41 +00001806 os << '"' << BIA->getArchName() << '"' << ", {"
Nico Weber5a459f82016-02-23 19:30:43 +00001807 << PrintActions1(C, *BIA->input_begin(), Ids) << "}";
Samuel Antaod06239d2016-07-15 23:13:27 +00001808 } else if (OffloadAction *OA = dyn_cast<OffloadAction>(A)) {
1809 bool IsFirst = true;
1810 OA->doOnEachDependence(
1811 [&](Action *A, const ToolChain *TC, const char *BoundArch) {
1812 // E.g. for two CUDA device dependences whose bound arch is sm_20 and
1813 // sm_35 this will generate:
1814 // "cuda-device" (nvptx64-nvidia-cuda:sm_20) {#ID}, "cuda-device"
1815 // (nvptx64-nvidia-cuda:sm_35) {#ID}
1816 if (!IsFirst)
1817 os << ", ";
1818 os << '"';
1819 if (TC)
1820 os << A->getOffloadingKindPrefix();
1821 else
1822 os << "host";
1823 os << " (";
1824 os << TC->getTriple().normalize();
1825
1826 if (BoundArch)
1827 os << ":" << BoundArch;
1828 os << ")";
1829 os << '"';
1830 os << " {" << PrintActions1(C, A, Ids) << "}";
1831 IsFirst = false;
1832 });
Daniel Dunbaraaf1ea62009-03-13 12:19:02 +00001833 } else {
Samuel Antaod06239d2016-07-15 23:13:27 +00001834 const ActionList *AL = &A->getInputs();
Artem Belevich0ff05cd2015-07-13 23:27:56 +00001835
Artem Belevich23256752015-09-22 17:23:09 +00001836 if (AL->size()) {
1837 const char *Prefix = "{";
1838 for (Action *PreRequisite : *AL) {
1839 os << Prefix << PrintActions1(C, PreRequisite, Ids);
1840 Prefix = ", ";
1841 }
1842 os << "}";
1843 } else
1844 os << "{}";
Daniel Dunbaraaf1ea62009-03-13 12:19:02 +00001845 }
1846
Samuel Antaod06239d2016-07-15 23:13:27 +00001847 // Append offload info for all options other than the offloading action
1848 // itself (e.g. (cuda-device, sm_20) or (cuda-host)).
1849 std::string offload_str;
1850 llvm::raw_string_ostream offload_os(offload_str);
1851 if (!isa<OffloadAction>(A)) {
1852 auto S = A->getOffloadingKindPrefix();
1853 if (!S.empty()) {
1854 offload_os << ", (" << S;
1855 if (A->getOffloadingArch())
1856 offload_os << ", " << A->getOffloadingArch();
1857 offload_os << ")";
1858 }
1859 }
1860
Daniel Dunbaraaf1ea62009-03-13 12:19:02 +00001861 unsigned Id = Ids.size();
1862 Ids[A] = Id;
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001863 llvm::errs() << Id << ": " << os.str() << ", "
Samuel Antaod06239d2016-07-15 23:13:27 +00001864 << types::getTypeName(A->getType()) << offload_os.str() << "\n";
Daniel Dunbaraaf1ea62009-03-13 12:19:02 +00001865
1866 return Id;
1867}
1868
Douglas Katzmanfd528672015-06-11 15:05:22 +00001869// Print the action graphs in a compilation C.
1870// For example "clang -c file1.c file2.c" is composed of two subgraphs.
Daniel Dunbareb843be2009-03-18 03:13:20 +00001871void Driver::PrintActions(const Compilation &C) const {
Douglas Katzmanb7e8ef02015-06-25 19:37:41 +00001872 std::map<Action *, unsigned> Ids;
1873 for (Action *A : C.getActions())
1874 PrintActions1(C, A, Ids);
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00001875}
1876
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001877/// Check whether the given input tree contains any compilation or
Joerg Sonnenberger5fe4a7d2011-05-06 14:05:11 +00001878/// assembly actions.
1879static bool ContainsCompileOrAssembleAction(const Action *A) {
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001880 if (isa<CompileJobAction>(A) || isa<BackendJobAction>(A) ||
Bob Wilson23a55f12014-12-21 07:00:00 +00001881 isa<AssembleJobAction>(A))
Daniel Dunbar00d3d8e2010-06-29 16:38:33 +00001882 return true;
1883
Nico Weber5a459f82016-02-23 19:30:43 +00001884 for (const Action *Input : A->inputs())
Nico Weberfb80f962015-09-19 21:36:51 +00001885 if (ContainsCompileOrAssembleAction(Input))
Daniel Dunbar00d3d8e2010-06-29 16:38:33 +00001886 return true;
1887
1888 return false;
1889}
1890
Artem Belevich5e2a3ec2015-11-17 22:28:40 +00001891void Driver::BuildUniversalActions(Compilation &C, const ToolChain &TC,
1892 const InputList &BAInputs) const {
1893 DerivedArgList &Args = C.getArgs();
1894 ActionList &Actions = C.getActions();
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001895 llvm::PrettyStackTraceString CrashInfo("Building universal build actions");
1896 // Collect the list of architectures. Duplicates are allowed, but should only
1897 // be handled once (in the order seen).
Daniel Dunbare5dc4822009-03-13 20:33:35 +00001898 llvm::StringSet<> ArchNames;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001899 SmallVector<const char *, 4> Archs;
Saleem Abdulrasool688b6bc2014-12-29 19:01:36 +00001900 for (Arg *A : Args) {
Daniel Dunbar0bfb21e2009-11-19 03:26:40 +00001901 if (A->getOption().matches(options::OPT_arch)) {
Daniel Dunbar9c3f7c42009-09-08 23:37:30 +00001902 // Validate the option here; we don't save the type here because its
1903 // particular spelling may participate in other driver choices.
1904 llvm::Triple::ArchType Arch =
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001905 tools::darwin::getArchTypeForMachOArchName(A->getValue());
Daniel Dunbar9c3f7c42009-09-08 23:37:30 +00001906 if (Arch == llvm::Triple::UnknownArch) {
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001907 Diag(clang::diag::err_drv_invalid_arch_name) << A->getAsString(Args);
Daniel Dunbar9c3f7c42009-09-08 23:37:30 +00001908 continue;
1909 }
1910
Daniel Dunbar2da02722009-03-19 07:55:12 +00001911 A->claim();
David Blaikie61b86d42014-11-19 02:56:13 +00001912 if (ArchNames.insert(A->getValue()).second)
Richard Smithbd55daf2012-11-01 04:30:05 +00001913 Archs.push_back(A->getValue());
Daniel Dunbarf479c122009-03-12 18:40:18 +00001914 }
1915 }
1916
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001917 // When there is no explicit arch for this platform, make sure we still bind
1918 // the architecture (to the default) so that -Xarch_ is handled correctly.
Daniel Dunbareb843be2009-03-18 03:13:20 +00001919 if (!Archs.size())
Daniel Dunbarc3bd9f52012-11-08 03:38:26 +00001920 Archs.push_back(Args.MakeArgString(TC.getDefaultUniversalArchName()));
Daniel Dunbarf479c122009-03-12 18:40:18 +00001921
Daniel Dunbarf479c122009-03-12 18:40:18 +00001922 ActionList SingleActions;
Justin Lebar0f3474c2016-02-11 02:00:50 +00001923 BuildActions(C, Args, BAInputs, SingleActions);
Daniel Dunbarf479c122009-03-12 18:40:18 +00001924
Daniel Dunbar6beaf512010-06-04 18:28:41 +00001925 // Add in arch bindings for every top level action, as well as lipo and
1926 // dsymutil steps if needed.
Nico Weberfb80f962015-09-19 21:36:51 +00001927 for (Action* Act : SingleActions) {
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001928 // Make sure we can lipo this kind of output. If not (and it is an actual
1929 // output) then we disallow, since we can't create an output file with the
1930 // right name without overwriting it. We could remove this oddity by just
1931 // changing the output names to include the arch, which would also fix
Daniel Dunbarf479c122009-03-12 18:40:18 +00001932 // -save-temps. Compatibility wins for now.
1933
Daniel Dunbare2ca3bd2009-03-13 17:46:02 +00001934 if (Archs.size() > 1 && !types::canLipoType(Act->getType()))
Daniel Dunbarf479c122009-03-12 18:40:18 +00001935 Diag(clang::diag::err_drv_invalid_output_with_multiple_archs)
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001936 << types::getTypeName(Act->getType());
Daniel Dunbarf479c122009-03-12 18:40:18 +00001937
1938 ActionList Inputs;
Justin Lebar41094612016-01-11 23:07:27 +00001939 for (unsigned i = 0, e = Archs.size(); i != e; ++i)
1940 Inputs.push_back(C.MakeAction<BindArchAction>(Act, Archs[i]));
Daniel Dunbarf479c122009-03-12 18:40:18 +00001941
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001942 // Lipo if necessary, we do it this way because we need to set the arch flag
1943 // so that -Xarch_ gets overwritten.
Daniel Dunbarf479c122009-03-12 18:40:18 +00001944 if (Inputs.size() == 1 || Act->getType() == types::TY_Nothing)
1945 Actions.append(Inputs.begin(), Inputs.end());
1946 else
Justin Lebar41094612016-01-11 23:07:27 +00001947 Actions.push_back(C.MakeAction<LipoJobAction>(Inputs, Act->getType()));
Daniel Dunbar6beaf512010-06-04 18:28:41 +00001948
Eric Christopher65c05fa2012-02-06 19:43:51 +00001949 // Handle debug info queries.
1950 Arg *A = Args.getLastArg(options::OPT_g_Group);
David Blaikie6f9f4eb2012-04-15 21:22:10 +00001951 if (A && !A->getOption().matches(options::OPT_g0) &&
1952 !A->getOption().matches(options::OPT_gstabs) &&
1953 ContainsCompileOrAssembleAction(Actions.back())) {
Chad Rosier62135492012-07-09 17:31:28 +00001954
David Blaikie6f9f4eb2012-04-15 21:22:10 +00001955 // Add a 'dsymutil' step if necessary, when debug info is enabled and we
1956 // have a compile input. We need to run 'dsymutil' ourselves in such cases
Eric Christopher776c26f2013-01-28 17:39:03 +00001957 // because the debug info will refer to a temporary object file which
David Blaikie6f9f4eb2012-04-15 21:22:10 +00001958 // will be removed at the end of the compilation process.
1959 if (Act->getType() == types::TY_Image) {
1960 ActionList Inputs;
1961 Inputs.push_back(Actions.back());
1962 Actions.pop_back();
Justin Lebar41094612016-01-11 23:07:27 +00001963 Actions.push_back(
1964 C.MakeAction<DsymutilJobAction>(Inputs, types::TY_dSYM));
Daniel Dunbar6beaf512010-06-04 18:28:41 +00001965 }
David Blaikie6f9f4eb2012-04-15 21:22:10 +00001966
Ben Langmuir9b9a8d32014-02-06 18:53:25 +00001967 // Verify the debug info output.
Alp Tokere9d2bfc2014-01-17 02:06:23 +00001968 if (Args.hasArg(options::OPT_verify_debug_info)) {
Justin Lebar41094612016-01-11 23:07:27 +00001969 Action* LastAction = Actions.back();
David Blaikie6f9f4eb2012-04-15 21:22:10 +00001970 Actions.pop_back();
Justin Lebar41094612016-01-11 23:07:27 +00001971 Actions.push_back(C.MakeAction<VerifyDebugInfoJobAction>(
1972 LastAction, types::TY_Nothing));
David Blaikie6f9f4eb2012-04-15 21:22:10 +00001973 }
1974 }
Daniel Dunbarf479c122009-03-12 18:40:18 +00001975 }
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00001976}
1977
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001978/// Check that the file referenced by Value exists. If it doesn't,
Hans Wennborg6ee64d52013-08-06 00:20:31 +00001979/// issue a diagnostic and return false.
Alp Toker8c8a8752013-12-03 06:53:35 +00001980static bool DiagnoseInputExistence(const Driver &D, const DerivedArgList &Args,
Hans Wennborg12f4f8b2016-04-15 01:12:32 +00001981 StringRef Value, types::ID Ty) {
Hans Wennborg6ee64d52013-08-06 00:20:31 +00001982 if (!D.getCheckInputsExist())
1983 return true;
1984
1985 // stdin always exists.
1986 if (Value == "-")
1987 return true;
1988
1989 SmallString<64> Path(Value);
1990 if (Arg *WorkDir = Args.getLastArg(options::OPT_working_directory)) {
Yaron Keren92e1b622015-03-18 10:17:07 +00001991 if (!llvm::sys::path::is_absolute(Path)) {
Hans Wennborg6ee64d52013-08-06 00:20:31 +00001992 SmallString<64> Directory(WorkDir->getValue());
1993 llvm::sys::path::append(Directory, Value);
1994 Path.assign(Directory);
1995 }
1996 }
1997
Sam McCall2c782472018-11-08 16:57:01 +00001998 if (D.getVFS().exists(Path))
Hans Wennborg6ee64d52013-08-06 00:20:31 +00001999 return true;
2000
Hans Wennborg12f4f8b2016-04-15 01:12:32 +00002001 if (D.IsCLMode()) {
2002 if (!llvm::sys::path::is_absolute(Twine(Path)) &&
2003 llvm::sys::Process::FindInEnvPath("LIB", Value))
2004 return true;
2005
2006 if (Args.hasArg(options::OPT__SLASH_link) && Ty == types::TY_Object) {
2007 // Arguments to the /link flag might cause the linker to search for object
2008 // and library files in paths we don't know about. Don't error in such
2009 // cases.
2010 return true;
2011 }
2012 }
Hans Wennborg23d26a32014-06-18 17:21:50 +00002013
Yaron Keren92e1b622015-03-18 10:17:07 +00002014 D.Diag(clang::diag::err_drv_no_such_file) << Path;
Hans Wennborg6ee64d52013-08-06 00:20:31 +00002015 return false;
2016}
2017
Chad Rosierecdede82011-08-12 22:08:57 +00002018// Construct a the list of inputs and their types.
Hans Wennborg55362852014-05-02 22:55:30 +00002019void Driver::BuildInputs(const ToolChain &TC, DerivedArgList &Args,
Chad Rosierecdede82011-08-12 22:08:57 +00002020 InputList &Inputs) const {
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00002021 // Track the current user specified (-x) input. We also explicitly track the
2022 // argument used to set the type; we only want to claim the type when we
2023 // actually use it, so we warn about unused -x arguments.
Daniel Dunbarc5a5ac52009-03-13 17:57:10 +00002024 types::ID InputType = types::TY_Nothing;
Craig Topper92fc2df2014-05-17 16:56:41 +00002025 Arg *InputTypeArg = nullptr;
Daniel Dunbarc5a5ac52009-03-13 17:57:10 +00002026
Hans Wennborg0d0b19c2013-08-12 18:34:17 +00002027 // The last /TC or /TP option sets the input type to C or C++ globally.
Ehsan Akhgaric249abb2014-09-12 21:44:24 +00002028 if (Arg *TCTP = Args.getLastArgNoClaim(options::OPT__SLASH_TC,
2029 options::OPT__SLASH_TP)) {
Hans Wennborg6ee64d52013-08-06 00:20:31 +00002030 InputTypeArg = TCTP;
Hans Wennborg0d0b19c2013-08-12 18:34:17 +00002031 InputType = TCTP->getOption().matches(options::OPT__SLASH_TC)
Douglas Katzmana67e50c2015-06-26 15:47:46 +00002032 ? types::TY_C
2033 : types::TY_CXX;
Hans Wennborg6ee64d52013-08-06 00:20:31 +00002034
Richard Smith0aef3052017-02-18 01:14:43 +00002035 Arg *Previous = nullptr;
Hans Wennborg0d0b19c2013-08-12 18:34:17 +00002036 bool ShowNote = false;
Simon Atanasyan27c0f202019-04-02 18:03:15 +00002037 for (Arg *A :
2038 Args.filtered(options::OPT__SLASH_TC, options::OPT__SLASH_TP)) {
Richard Smith0aef3052017-02-18 01:14:43 +00002039 if (Previous) {
2040 Diag(clang::diag::warn_drv_overriding_flag_option)
2041 << Previous->getSpelling() << A->getSpelling();
2042 ShowNote = true;
2043 }
2044 Previous = A;
Hans Wennborg6ee64d52013-08-06 00:20:31 +00002045 }
Hans Wennborg0d0b19c2013-08-12 18:34:17 +00002046 if (ShowNote)
2047 Diag(clang::diag::note_drv_t_option_is_global);
Hans Wennborg6ee64d52013-08-06 00:20:31 +00002048
2049 // No driver mode exposes -x and /TC or /TP; we don't support mixing them.
2050 assert(!Args.hasArg(options::OPT_x) && "-x and /TC or /TP is not allowed");
2051 }
2052
Saleem Abdulrasool688b6bc2014-12-29 19:01:36 +00002053 for (Arg *A : Args) {
Michael J. Spencerad3ccc32012-08-20 21:41:17 +00002054 if (A->getOption().getKind() == Option::InputClass) {
Richard Smithbd55daf2012-11-01 04:30:05 +00002055 const char *Value = A->getValue();
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00002056 types::ID Ty = types::TY_INVALID;
2057
2058 // Infer the input type if necessary.
Daniel Dunbarc5a5ac52009-03-13 17:57:10 +00002059 if (InputType == types::TY_Nothing) {
2060 // If there was an explicit arg for this, claim it.
2061 if (InputTypeArg)
2062 InputTypeArg->claim();
2063
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00002064 // stdin must be handled specially.
2065 if (memcmp(Value, "-", 2) == 0) {
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00002066 // If running with -E, treat as a C input (this changes the builtin
2067 // macros, for example). This may be overridden by -ObjC below.
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00002068 //
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00002069 // Otherwise emit an error but still use a valid type to avoid
2070 // spurious errors (e.g., no inputs).
Hans Wennborg70850d82013-07-18 20:29:38 +00002071 if (!Args.hasArgNoClaim(options::OPT_E) && !CCCIsCPP())
Hans Wennborgcfdd8b52014-01-29 01:04:40 +00002072 Diag(IsCLMode() ? clang::diag::err_drv_unknown_stdin_type_clang_cl
2073 : clang::diag::err_drv_unknown_stdin_type);
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00002074 Ty = types::TY_C;
2075 } else {
Joerg Sonnenbergerbdbdf702011-03-16 22:45:02 +00002076 // Otherwise lookup by extension.
Reid Klecknera643e642018-12-26 21:04:08 +00002077 // Fallback is C if invoked as C preprocessor, C++ if invoked with
2078 // clang-cl /E, or Object otherwise.
Joerg Sonnenbergerbdbdf702011-03-16 22:45:02 +00002079 // We use a host hook here because Darwin at least has its own
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00002080 // idea of what .s is.
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00002081 if (const char *Ext = strrchr(Value, '.'))
Daniel Dunbarcc7df6c2010-08-02 05:43:56 +00002082 Ty = TC.LookupTypeForExtension(Ext + 1);
Daniel Dunbarea9f0322009-03-20 23:39:23 +00002083
Joerg Sonnenbergerbdbdf702011-03-16 22:45:02 +00002084 if (Ty == types::TY_INVALID) {
Hans Wennborg70850d82013-07-18 20:29:38 +00002085 if (CCCIsCPP())
Joerg Sonnenbergerbdbdf702011-03-16 22:45:02 +00002086 Ty = types::TY_C;
Reid Klecknera643e642018-12-26 21:04:08 +00002087 else if (IsCLMode() && Args.hasArgNoClaim(options::OPT_E))
2088 Ty = types::TY_CXX;
Joerg Sonnenbergerbdbdf702011-03-16 22:45:02 +00002089 else
2090 Ty = types::TY_Object;
2091 }
Daniel Dunbar0ac94452010-02-17 20:32:58 +00002092
2093 // If the driver is invoked as C++ compiler (like clang++ or c++) it
2094 // should autodetect some input files as C++ for g++ compatibility.
Hans Wennborg70850d82013-07-18 20:29:38 +00002095 if (CCCIsCXX()) {
Daniel Dunbar0ac94452010-02-17 20:32:58 +00002096 types::ID OldTy = Ty;
2097 Ty = types::lookupCXXTypeForCType(Ty);
2098
2099 if (Ty != OldTy)
2100 Diag(clang::diag::warn_drv_treating_input_as_cxx)
Douglas Katzmana67e50c2015-06-26 15:47:46 +00002101 << getTypeName(OldTy) << getTypeName(Ty);
Daniel Dunbar0ac94452010-02-17 20:32:58 +00002102 }
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00002103 }
2104
Daniel Dunbar82b22102009-05-18 21:47:54 +00002105 // -ObjC and -ObjC++ override the default language, but only for "source
2106 // files". We just treat everything that isn't a linker input as a
2107 // source file.
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00002108 //
Daniel Dunbar82b22102009-05-18 21:47:54 +00002109 // FIXME: Clean this up if we move the phase sequence into the type.
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00002110 if (Ty != types::TY_Object) {
2111 if (Args.hasArg(options::OPT_ObjC))
2112 Ty = types::TY_ObjC;
2113 else if (Args.hasArg(options::OPT_ObjCXX))
2114 Ty = types::TY_ObjCXX;
2115 }
2116 } else {
2117 assert(InputTypeArg && "InputType set w/o InputTypeArg");
Ehsan Akhgari7e954ea2014-09-12 18:15:10 +00002118 if (!InputTypeArg->getOption().matches(options::OPT_x)) {
2119 // If emulating cl.exe, make sure that /TC and /TP don't affect input
2120 // object files.
2121 const char *Ext = strrchr(Value, '.');
2122 if (Ext && TC.LookupTypeForExtension(Ext + 1) == types::TY_Object)
2123 Ty = types::TY_Object;
2124 }
2125 if (Ty == types::TY_INVALID) {
2126 Ty = InputType;
2127 InputTypeArg->claim();
2128 }
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00002129 }
2130
Hans Wennborg12f4f8b2016-04-15 01:12:32 +00002131 if (DiagnoseInputExistence(*this, Args, Value, Ty))
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00002132 Inputs.push_back(std::make_pair(Ty, A));
2133
Hans Wennborg6ee64d52013-08-06 00:20:31 +00002134 } else if (A->getOption().matches(options::OPT__SLASH_Tc)) {
2135 StringRef Value = A->getValue();
Hans Wennborg12f4f8b2016-04-15 01:12:32 +00002136 if (DiagnoseInputExistence(*this, Args, Value, types::TY_C)) {
David Blaikie0aaa7622017-01-13 17:34:15 +00002137 Arg *InputArg = MakeInputArg(Args, *Opts, A->getValue());
Hans Wennborg6ee64d52013-08-06 00:20:31 +00002138 Inputs.push_back(std::make_pair(types::TY_C, InputArg));
2139 }
2140 A->claim();
2141 } else if (A->getOption().matches(options::OPT__SLASH_Tp)) {
2142 StringRef Value = A->getValue();
Hans Wennborg12f4f8b2016-04-15 01:12:32 +00002143 if (DiagnoseInputExistence(*this, Args, Value, types::TY_CXX)) {
David Blaikie0aaa7622017-01-13 17:34:15 +00002144 Arg *InputArg = MakeInputArg(Args, *Opts, A->getValue());
Hans Wennborg6ee64d52013-08-06 00:20:31 +00002145 Inputs.push_back(std::make_pair(types::TY_CXX, InputArg));
2146 }
2147 A->claim();
Michael J. Spencer66e2b202012-10-19 22:37:06 +00002148 } else if (A->getOption().hasFlag(options::LinkerInput)) {
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00002149 // Just treat as object type, we could make a special type for this if
2150 // necessary.
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00002151 Inputs.push_back(std::make_pair(types::TY_Object, A));
2152
Daniel Dunbar0bfb21e2009-11-19 03:26:40 +00002153 } else if (A->getOption().matches(options::OPT_x)) {
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00002154 InputTypeArg = A;
Richard Smithbd55daf2012-11-01 04:30:05 +00002155 InputType = types::lookupTypeForTypeSpecifier(A->getValue());
Chad Rosier706c2352012-04-07 00:01:31 +00002156 A->claim();
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00002157
2158 // Follow gcc behavior and treat as linker input for invalid -x
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00002159 // options. Its not clear why we shouldn't just revert to unknown; but
Michael J. Spencer1a4fe8c2010-12-17 21:22:33 +00002160 // this isn't very important, we might as well be bug compatible.
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00002161 if (!InputType) {
Richard Smithbd55daf2012-11-01 04:30:05 +00002162 Diag(clang::diag::err_drv_unknown_language) << A->getValue();
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00002163 InputType = types::TY_Object;
2164 }
Hans Wennborg091f1b62017-01-27 17:09:41 +00002165 } else if (A->getOption().getID() == options::OPT__SLASH_U) {
2166 assert(A->getNumValues() == 1 && "The /U option has one value.");
2167 StringRef Val = A->getValue(0);
2168 if (Val.find_first_of("/\\") != StringRef::npos) {
2169 // Warn about e.g. "/Users/me/myfile.c".
2170 Diag(diag::warn_slash_u_filename) << Val;
2171 Diag(diag::note_use_dashdash);
2172 }
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00002173 }
2174 }
Hans Wennborg70850d82013-07-18 20:29:38 +00002175 if (CCCIsCPP() && Inputs.empty()) {
Joerg Sonnenbergerb86f5f42011-03-06 23:31:01 +00002176 // If called as standalone preprocessor, stdin is processed
2177 // if no other input is present.
David Blaikie0aaa7622017-01-13 17:34:15 +00002178 Arg *A = MakeInputArg(Args, *Opts, "-");
Joerg Sonnenbergerb86f5f42011-03-06 23:31:01 +00002179 Inputs.push_back(std::make_pair(types::TY_C, A));
2180 }
Chad Rosierecdede82011-08-12 22:08:57 +00002181}
2182
Samuel Antao64e965e2016-09-30 15:34:19 +00002183namespace {
2184/// Provides a convenient interface for different programming models to generate
2185/// the required device actions.
2186class OffloadingActionBuilder final {
2187 /// Flag used to trace errors in the builder.
2188 bool IsValid = false;
2189
2190 /// The compilation that is using this builder.
2191 Compilation &C;
2192
Samuel Antao64e965e2016-09-30 15:34:19 +00002193 /// Map between an input argument and the offload kinds used to process it.
2194 std::map<const Arg *, unsigned> InputArgToOffloadKindMap;
2195
2196 /// Builder interface. It doesn't build anything or keep any state.
2197 class DeviceActionBuilder {
2198 public:
2199 typedef llvm::SmallVector<phases::ID, phases::MaxNumberOfPhases> PhasesTy;
2200
2201 enum ActionBuilderReturnCode {
2202 // The builder acted successfully on the current action.
2203 ABRT_Success,
2204 // The builder didn't have to act on the current action.
2205 ABRT_Inactive,
2206 // The builder was successful and requested the host action to not be
2207 // generated.
2208 ABRT_Ignore_Host,
2209 };
2210
2211 protected:
2212 /// Compilation associated with this builder.
2213 Compilation &C;
2214
2215 /// Tool chains associated with this builder. The same programming
2216 /// model may have associated one or more tool chains.
2217 SmallVector<const ToolChain *, 2> ToolChains;
2218
2219 /// The derived arguments associated with this builder.
2220 DerivedArgList &Args;
2221
2222 /// The inputs associated with this builder.
2223 const Driver::InputList &Inputs;
2224
2225 /// The associated offload kind.
2226 Action::OffloadKind AssociatedOffloadKind = Action::OFK_None;
2227
2228 public:
2229 DeviceActionBuilder(Compilation &C, DerivedArgList &Args,
2230 const Driver::InputList &Inputs,
2231 Action::OffloadKind AssociatedOffloadKind)
2232 : C(C), Args(Args), Inputs(Inputs),
2233 AssociatedOffloadKind(AssociatedOffloadKind) {}
2234 virtual ~DeviceActionBuilder() {}
2235
2236 /// Fill up the array \a DA with all the device dependences that should be
2237 /// added to the provided host action \a HostAction. By default it is
2238 /// inactive.
2239 virtual ActionBuilderReturnCode
Samuel Antao28c4f182016-10-27 17:08:03 +00002240 getDeviceDependences(OffloadAction::DeviceDependences &DA,
2241 phases::ID CurPhase, phases::ID FinalPhase,
2242 PhasesTy &Phases) {
Samuel Antao64e965e2016-09-30 15:34:19 +00002243 return ABRT_Inactive;
2244 }
2245
2246 /// Update the state to include the provided host action \a HostAction as a
2247 /// dependency of the current device action. By default it is inactive.
2248 virtual ActionBuilderReturnCode addDeviceDepences(Action *HostAction) {
2249 return ABRT_Inactive;
2250 }
2251
2252 /// Append top level actions generated by the builder. Return true if errors
2253 /// were found.
2254 virtual void appendTopLevelActions(ActionList &AL) {}
2255
2256 /// Append linker actions generated by the builder. Return true if errors
2257 /// were found.
2258 virtual void appendLinkDependences(OffloadAction::DeviceDependences &DA) {}
2259
2260 /// Initialize the builder. Return true if any initialization errors are
2261 /// found.
2262 virtual bool initialize() { return false; }
2263
Samuel Antao69d6f312016-10-27 17:50:43 +00002264 /// Return true if the builder can use bundling/unbundling.
2265 virtual bool canUseBundlerUnbundler() const { return false; }
2266
Samuel Antao64e965e2016-09-30 15:34:19 +00002267 /// Return true if this builder is valid. We have a valid builder if we have
2268 /// associated device tool chains.
2269 bool isValid() { return !ToolChains.empty(); }
2270
2271 /// Return the associated offload kind.
2272 Action::OffloadKind getAssociatedOffloadKind() {
2273 return AssociatedOffloadKind;
2274 }
2275 };
2276
Yaxun Liu3af038b2018-05-30 00:49:10 +00002277 /// Base class for CUDA/HIP action builder. It injects device code in
2278 /// the host backend action.
2279 class CudaActionBuilderBase : public DeviceActionBuilder {
2280 protected:
Samuel Antao64e965e2016-09-30 15:34:19 +00002281 /// Flags to signal if the user requested host-only or device-only
2282 /// compilation.
2283 bool CompileHostOnly = false;
2284 bool CompileDeviceOnly = false;
2285
2286 /// List of GPU architectures to use in this compilation.
2287 SmallVector<CudaArch, 4> GpuArchList;
2288
2289 /// The CUDA actions for the current input.
2290 ActionList CudaDeviceActions;
2291
2292 /// The CUDA fat binary if it was generated for the current input.
2293 Action *CudaFatBinary = nullptr;
2294
2295 /// Flag that is set to true if this builder acted on the current input.
2296 bool IsActive = false;
Yaxun Liuab851932019-03-05 16:07:56 +00002297
2298 /// Flag for -fgpu-rdc.
2299 bool Relocatable = false;
Yaxun Liu3af038b2018-05-30 00:49:10 +00002300 public:
2301 CudaActionBuilderBase(Compilation &C, DerivedArgList &Args,
2302 const Driver::InputList &Inputs,
2303 Action::OffloadKind OFKind)
2304 : DeviceActionBuilder(C, Args, Inputs, OFKind) {}
Samuel Antao64e965e2016-09-30 15:34:19 +00002305
Yaxun Liu3af038b2018-05-30 00:49:10 +00002306 ActionBuilderReturnCode addDeviceDepences(Action *HostAction) override {
2307 // While generating code for CUDA, we only depend on the host input action
2308 // to trigger the creation of all the CUDA device actions.
2309
2310 // If we are dealing with an input action, replicate it for each GPU
2311 // architecture. If we are in host-only mode we return 'success' so that
2312 // the host uses the CUDA offload kind.
2313 if (auto *IA = dyn_cast<InputAction>(HostAction)) {
2314 assert(!GpuArchList.empty() &&
2315 "We should have at least one GPU architecture.");
2316
2317 // If the host input is not CUDA or HIP, we don't need to bother about
2318 // this input.
2319 if (IA->getType() != types::TY_CUDA &&
2320 IA->getType() != types::TY_HIP) {
2321 // The builder will ignore this input.
2322 IsActive = false;
2323 return ABRT_Inactive;
2324 }
2325
2326 // Set the flag to true, so that the builder acts on the current input.
2327 IsActive = true;
2328
2329 if (CompileHostOnly)
2330 return ABRT_Success;
2331
2332 // Replicate inputs for each GPU architecture.
2333 auto Ty = IA->getType() == types::TY_HIP ? types::TY_HIP_DEVICE
2334 : types::TY_CUDA_DEVICE;
2335 for (unsigned I = 0, E = GpuArchList.size(); I != E; ++I) {
2336 CudaDeviceActions.push_back(
2337 C.MakeAction<InputAction>(IA->getInputArg(), Ty));
2338 }
2339
2340 return ABRT_Success;
2341 }
2342
2343 // If this is an unbundling action use it as is for each CUDA toolchain.
2344 if (auto *UA = dyn_cast<OffloadUnbundlingJobAction>(HostAction)) {
Yaxun Liuab851932019-03-05 16:07:56 +00002345
2346 // If -fgpu-rdc is disabled, should not unbundle since there is no
2347 // device code to link.
2348 if (!Relocatable)
2349 return ABRT_Inactive;
2350
Yaxun Liu3af038b2018-05-30 00:49:10 +00002351 CudaDeviceActions.clear();
Aaron Enye Shibea57bb2019-01-04 19:05:41 +00002352 auto *IA = cast<InputAction>(UA->getInputs().back());
2353 std::string FileName = IA->getInputArg().getAsString(Args);
2354 // Check if the type of the file is the same as the action. Do not
2355 // unbundle it if it is not. Do not unbundle .so files, for example,
2356 // which are not object files.
2357 if (IA->getType() == types::TY_Object &&
2358 (!llvm::sys::path::has_extension(FileName) ||
2359 types::lookupTypeForExtension(
2360 llvm::sys::path::extension(FileName).drop_front()) !=
2361 types::TY_Object))
2362 return ABRT_Inactive;
2363
Yaxun Liu3af038b2018-05-30 00:49:10 +00002364 for (auto Arch : GpuArchList) {
2365 CudaDeviceActions.push_back(UA);
2366 UA->registerDependentActionInfo(ToolChains[0], CudaArchToString(Arch),
2367 AssociatedOffloadKind);
2368 }
2369 return ABRT_Success;
2370 }
2371
2372 return IsActive ? ABRT_Success : ABRT_Inactive;
2373 }
2374
2375 void appendTopLevelActions(ActionList &AL) override {
2376 // Utility to append actions to the top level list.
2377 auto AddTopLevel = [&](Action *A, CudaArch BoundArch) {
2378 OffloadAction::DeviceDependences Dep;
2379 Dep.add(*A, *ToolChains.front(), CudaArchToString(BoundArch),
2380 AssociatedOffloadKind);
2381 AL.push_back(C.MakeAction<OffloadAction>(Dep, A->getType()));
2382 };
2383
2384 // If we have a fat binary, add it to the list.
2385 if (CudaFatBinary) {
2386 AddTopLevel(CudaFatBinary, CudaArch::UNKNOWN);
2387 CudaDeviceActions.clear();
2388 CudaFatBinary = nullptr;
2389 return;
2390 }
2391
2392 if (CudaDeviceActions.empty())
2393 return;
2394
2395 // If we have CUDA actions at this point, that's because we have a have
2396 // partial compilation, so we should have an action for each GPU
2397 // architecture.
2398 assert(CudaDeviceActions.size() == GpuArchList.size() &&
2399 "Expecting one action per GPU architecture.");
2400 assert(ToolChains.size() == 1 &&
2401 "Expecting to have a sing CUDA toolchain.");
2402 for (unsigned I = 0, E = GpuArchList.size(); I != E; ++I)
2403 AddTopLevel(CudaDeviceActions[I], GpuArchList[I]);
2404
2405 CudaDeviceActions.clear();
2406 }
2407
2408 bool initialize() override {
2409 assert(AssociatedOffloadKind == Action::OFK_Cuda ||
2410 AssociatedOffloadKind == Action::OFK_HIP);
2411
2412 // We don't need to support CUDA.
2413 if (AssociatedOffloadKind == Action::OFK_Cuda &&
2414 !C.hasOffloadToolChain<Action::OFK_Cuda>())
2415 return false;
2416
2417 // We don't need to support HIP.
2418 if (AssociatedOffloadKind == Action::OFK_HIP &&
2419 !C.hasOffloadToolChain<Action::OFK_HIP>())
2420 return false;
2421
Yaxun Liuab851932019-03-05 16:07:56 +00002422 Relocatable = Args.hasFlag(options::OPT_fgpu_rdc,
2423 options::OPT_fno_gpu_rdc, /*Default=*/false);
2424
Yaxun Liu3af038b2018-05-30 00:49:10 +00002425 const ToolChain *HostTC = C.getSingleOffloadToolChain<Action::OFK_Host>();
2426 assert(HostTC && "No toolchain for host compilation.");
2427 if (HostTC->getTriple().isNVPTX() ||
2428 HostTC->getTriple().getArch() == llvm::Triple::amdgcn) {
2429 // We do not support targeting NVPTX/AMDGCN for host compilation. Throw
2430 // an error and abort pipeline construction early so we don't trip
2431 // asserts that assume device-side compilation.
2432 C.getDriver().Diag(diag::err_drv_cuda_host_arch)
2433 << HostTC->getTriple().getArchName();
2434 return true;
2435 }
2436
2437 ToolChains.push_back(
2438 AssociatedOffloadKind == Action::OFK_Cuda
2439 ? C.getSingleOffloadToolChain<Action::OFK_Cuda>()
2440 : C.getSingleOffloadToolChain<Action::OFK_HIP>());
2441
2442 Arg *PartialCompilationArg = Args.getLastArg(
2443 options::OPT_cuda_host_only, options::OPT_cuda_device_only,
2444 options::OPT_cuda_compile_host_device);
2445 CompileHostOnly = PartialCompilationArg &&
2446 PartialCompilationArg->getOption().matches(
2447 options::OPT_cuda_host_only);
2448 CompileDeviceOnly = PartialCompilationArg &&
2449 PartialCompilationArg->getOption().matches(
2450 options::OPT_cuda_device_only);
2451
2452 // Collect all cuda_gpu_arch parameters, removing duplicates.
2453 std::set<CudaArch> GpuArchs;
2454 bool Error = false;
2455 for (Arg *A : Args) {
2456 if (!(A->getOption().matches(options::OPT_cuda_gpu_arch_EQ) ||
2457 A->getOption().matches(options::OPT_no_cuda_gpu_arch_EQ)))
2458 continue;
2459 A->claim();
2460
2461 const StringRef ArchStr = A->getValue();
2462 if (A->getOption().matches(options::OPT_no_cuda_gpu_arch_EQ) &&
2463 ArchStr == "all") {
2464 GpuArchs.clear();
2465 continue;
2466 }
2467 CudaArch Arch = StringToCudaArch(ArchStr);
2468 if (Arch == CudaArch::UNKNOWN) {
2469 C.getDriver().Diag(clang::diag::err_drv_cuda_bad_gpu_arch) << ArchStr;
2470 Error = true;
2471 } else if (A->getOption().matches(options::OPT_cuda_gpu_arch_EQ))
2472 GpuArchs.insert(Arch);
2473 else if (A->getOption().matches(options::OPT_no_cuda_gpu_arch_EQ))
2474 GpuArchs.erase(Arch);
2475 else
2476 llvm_unreachable("Unexpected option.");
2477 }
2478
2479 // Collect list of GPUs remaining in the set.
2480 for (CudaArch Arch : GpuArchs)
2481 GpuArchList.push_back(Arch);
2482
2483 // Default to sm_20 which is the lowest common denominator for
2484 // supported GPUs. sm_20 code should work correctly, if
2485 // suboptimally, on all newer GPUs.
2486 if (GpuArchList.empty())
2487 GpuArchList.push_back(CudaArch::SM_20);
2488
2489 return Error;
2490 }
2491 };
2492
2493 /// \brief CUDA action builder. It injects device code in the host backend
2494 /// action.
2495 class CudaActionBuilder final : public CudaActionBuilderBase {
Samuel Antao64e965e2016-09-30 15:34:19 +00002496 public:
2497 CudaActionBuilder(Compilation &C, DerivedArgList &Args,
2498 const Driver::InputList &Inputs)
Yaxun Liu3af038b2018-05-30 00:49:10 +00002499 : CudaActionBuilderBase(C, Args, Inputs, Action::OFK_Cuda) {}
Samuel Antao64e965e2016-09-30 15:34:19 +00002500
2501 ActionBuilderReturnCode
Samuel Antao28c4f182016-10-27 17:08:03 +00002502 getDeviceDependences(OffloadAction::DeviceDependences &DA,
2503 phases::ID CurPhase, phases::ID FinalPhase,
2504 PhasesTy &Phases) override {
Samuel Antao64e965e2016-09-30 15:34:19 +00002505 if (!IsActive)
2506 return ABRT_Inactive;
2507
2508 // If we don't have more CUDA actions, we don't have any dependences to
2509 // create for the host.
2510 if (CudaDeviceActions.empty())
2511 return ABRT_Success;
2512
2513 assert(CudaDeviceActions.size() == GpuArchList.size() &&
2514 "Expecting one action per GPU architecture.");
2515 assert(!CompileHostOnly &&
2516 "Not expecting CUDA actions in host-only compilation.");
2517
2518 // If we are generating code for the device or we are in a backend phase,
2519 // we attempt to generate the fat binary. We compile each arch to ptx and
2520 // assemble to cubin, then feed the cubin *and* the ptx into a device
2521 // "link" action, which uses fatbinary to combine these cubins into one
2522 // fatbin. The fatbin is then an input to the host action if not in
2523 // device-only mode.
2524 if (CompileDeviceOnly || CurPhase == phases::Backend) {
2525 ActionList DeviceActions;
2526 for (unsigned I = 0, E = GpuArchList.size(); I != E; ++I) {
2527 // Produce the device action from the current phase up to the assemble
2528 // phase.
2529 for (auto Ph : Phases) {
2530 // Skip the phases that were already dealt with.
2531 if (Ph < CurPhase)
2532 continue;
2533 // We have to be consistent with the host final phase.
2534 if (Ph > FinalPhase)
2535 break;
2536
2537 CudaDeviceActions[I] = C.getDriver().ConstructPhaseAction(
Artem Belevichecb178b2018-03-21 22:22:59 +00002538 C, Args, Ph, CudaDeviceActions[I], Action::OFK_Cuda);
Samuel Antao64e965e2016-09-30 15:34:19 +00002539
2540 if (Ph == phases::Assemble)
2541 break;
2542 }
2543
2544 // If we didn't reach the assemble phase, we can't generate the fat
2545 // binary. We don't need to generate the fat binary if we are not in
2546 // device-only mode.
2547 if (!isa<AssembleJobAction>(CudaDeviceActions[I]) ||
2548 CompileDeviceOnly)
2549 continue;
2550
2551 Action *AssembleAction = CudaDeviceActions[I];
2552 assert(AssembleAction->getType() == types::TY_Object);
2553 assert(AssembleAction->getInputs().size() == 1);
2554
2555 Action *BackendAction = AssembleAction->getInputs()[0];
2556 assert(BackendAction->getType() == types::TY_PP_Asm);
2557
2558 for (auto &A : {AssembleAction, BackendAction}) {
2559 OffloadAction::DeviceDependences DDep;
2560 DDep.add(*A, *ToolChains.front(), CudaArchToString(GpuArchList[I]),
2561 Action::OFK_Cuda);
2562 DeviceActions.push_back(
2563 C.MakeAction<OffloadAction>(DDep, A->getType()));
2564 }
2565 }
2566
2567 // We generate the fat binary if we have device input actions.
2568 if (!DeviceActions.empty()) {
2569 CudaFatBinary =
2570 C.MakeAction<LinkJobAction>(DeviceActions, types::TY_CUDA_FATBIN);
2571
2572 if (!CompileDeviceOnly) {
2573 DA.add(*CudaFatBinary, *ToolChains.front(), /*BoundArch=*/nullptr,
2574 Action::OFK_Cuda);
2575 // Clear the fat binary, it is already a dependence to an host
2576 // action.
2577 CudaFatBinary = nullptr;
2578 }
2579
2580 // Remove the CUDA actions as they are already connected to an host
2581 // action or fat binary.
2582 CudaDeviceActions.clear();
2583 }
2584
2585 // We avoid creating host action in device-only mode.
2586 return CompileDeviceOnly ? ABRT_Ignore_Host : ABRT_Success;
Samuel Antao5b1a89a2016-10-27 00:53:34 +00002587 } else if (CurPhase > phases::Backend) {
2588 // If we are past the backend phase and still have a device action, we
2589 // don't have to do anything as this action is already a device
2590 // top-level action.
2591 return ABRT_Success;
Samuel Antao64e965e2016-09-30 15:34:19 +00002592 }
2593
2594 assert(CurPhase < phases::Backend && "Generating single CUDA "
2595 "instructions should only occur "
2596 "before the backend phase!");
2597
2598 // By default, we produce an action for each device arch.
2599 for (Action *&A : CudaDeviceActions)
2600 A = C.getDriver().ConstructPhaseAction(C, Args, CurPhase, A);
2601
2602 return ABRT_Success;
2603 }
Yaxun Liu3af038b2018-05-30 00:49:10 +00002604 };
2605 /// \brief HIP action builder. It injects device code in the host backend
2606 /// action.
2607 class HIPActionBuilder final : public CudaActionBuilderBase {
2608 /// The linker inputs obtained for each device arch.
2609 SmallVector<ActionList, 8> DeviceLinkerInputs;
Samuel Antao64e965e2016-09-30 15:34:19 +00002610
Yaxun Liu3af038b2018-05-30 00:49:10 +00002611 public:
2612 HIPActionBuilder(Compilation &C, DerivedArgList &Args,
2613 const Driver::InputList &Inputs)
Yaxun Liuab851932019-03-05 16:07:56 +00002614 : CudaActionBuilderBase(C, Args, Inputs, Action::OFK_HIP) {}
Samuel Antao64e965e2016-09-30 15:34:19 +00002615
Yaxun Liu3af038b2018-05-30 00:49:10 +00002616 bool canUseBundlerUnbundler() const override { return true; }
Samuel Antao64e965e2016-09-30 15:34:19 +00002617
Yaxun Liu3af038b2018-05-30 00:49:10 +00002618 ActionBuilderReturnCode
2619 getDeviceDependences(OffloadAction::DeviceDependences &DA,
2620 phases::ID CurPhase, phases::ID FinalPhase,
2621 PhasesTy &Phases) override {
2622 // amdgcn does not support linking of object files, therefore we skip
Yaxun Liu97670892018-10-02 17:48:54 +00002623 // backend and assemble phases to output LLVM IR. Except for generating
2624 // non-relocatable device coee, where we generate fat binary for device
2625 // code and pass to host in Backend phase.
2626 if (CudaDeviceActions.empty() ||
2627 (CurPhase == phases::Backend && Relocatable) ||
Yaxun Liu3af038b2018-05-30 00:49:10 +00002628 CurPhase == phases::Assemble)
2629 return ABRT_Success;
2630
Yaxun Liu97670892018-10-02 17:48:54 +00002631 assert(((CurPhase == phases::Link && Relocatable) ||
Yaxun Liu3af038b2018-05-30 00:49:10 +00002632 CudaDeviceActions.size() == GpuArchList.size()) &&
2633 "Expecting one action per GPU architecture.");
2634 assert(!CompileHostOnly &&
2635 "Not expecting CUDA actions in host-only compilation.");
2636
Yaxun Liu97670892018-10-02 17:48:54 +00002637 if (!Relocatable && CurPhase == phases::Backend) {
2638 // If we are in backend phase, we attempt to generate the fat binary.
2639 // We compile each arch to IR and use a link action to generate code
2640 // object containing ISA. Then we use a special "link" action to create
2641 // a fat binary containing all the code objects for different GPU's.
2642 // The fat binary is then an input to the host action.
2643 for (unsigned I = 0, E = GpuArchList.size(); I != E; ++I) {
2644 // Create a link action to link device IR with device library
2645 // and generate ISA.
2646 ActionList AL;
2647 AL.push_back(CudaDeviceActions[I]);
2648 CudaDeviceActions[I] =
2649 C.MakeAction<LinkJobAction>(AL, types::TY_Image);
2650
2651 // OffloadingActionBuilder propagates device arch until an offload
2652 // action. Since the next action for creating fatbin does
2653 // not have device arch, whereas the above link action and its input
2654 // have device arch, an offload action is needed to stop the null
2655 // device arch of the next action being propagated to the above link
2656 // action.
2657 OffloadAction::DeviceDependences DDep;
2658 DDep.add(*CudaDeviceActions[I], *ToolChains.front(),
2659 CudaArchToString(GpuArchList[I]), AssociatedOffloadKind);
2660 CudaDeviceActions[I] = C.MakeAction<OffloadAction>(
2661 DDep, CudaDeviceActions[I]->getType());
2662 }
2663 // Create HIP fat binary with a special "link" action.
2664 CudaFatBinary =
2665 C.MakeAction<LinkJobAction>(CudaDeviceActions,
2666 types::TY_HIP_FATBIN);
2667
Yaxun Liu2bcc9512018-11-14 04:47:31 +00002668 if (!CompileDeviceOnly) {
2669 DA.add(*CudaFatBinary, *ToolChains.front(), /*BoundArch=*/nullptr,
2670 AssociatedOffloadKind);
2671 // Clear the fat binary, it is already a dependence to an host
2672 // action.
2673 CudaFatBinary = nullptr;
2674 }
Yaxun Liu97670892018-10-02 17:48:54 +00002675
2676 // Remove the CUDA actions as they are already connected to an host
2677 // action or fat binary.
2678 CudaDeviceActions.clear();
2679
Yaxun Liu2bcc9512018-11-14 04:47:31 +00002680 return CompileDeviceOnly ? ABRT_Ignore_Host : ABRT_Success;
Yaxun Liu97670892018-10-02 17:48:54 +00002681 } else if (CurPhase == phases::Link) {
2682 // Save CudaDeviceActions to DeviceLinkerInputs for each GPU subarch.
2683 // This happens to each device action originated from each input file.
2684 // Later on, device actions in DeviceLinkerInputs are used to create
2685 // device link actions in appendLinkDependences and the created device
2686 // link actions are passed to the offload action as device dependence.
Yaxun Liu3af038b2018-05-30 00:49:10 +00002687 DeviceLinkerInputs.resize(CudaDeviceActions.size());
2688 auto LI = DeviceLinkerInputs.begin();
2689 for (auto *A : CudaDeviceActions) {
2690 LI->push_back(A);
2691 ++LI;
Samuel Antao64e965e2016-09-30 15:34:19 +00002692 }
2693
Yaxun Liu3af038b2018-05-30 00:49:10 +00002694 // We will pass the device action as a host dependence, so we don't
2695 // need to do anything else with them.
2696 CudaDeviceActions.clear();
Samuel Antao64e965e2016-09-30 15:34:19 +00002697 return ABRT_Success;
2698 }
2699
Yaxun Liu3af038b2018-05-30 00:49:10 +00002700 // By default, we produce an action for each device arch.
2701 for (Action *&A : CudaDeviceActions)
2702 A = C.getDriver().ConstructPhaseAction(C, Args, CurPhase, A,
2703 AssociatedOffloadKind);
2704
2705 return ABRT_Success;
Samuel Antao64e965e2016-09-30 15:34:19 +00002706 }
2707
Yaxun Liu3af038b2018-05-30 00:49:10 +00002708 void appendLinkDependences(OffloadAction::DeviceDependences &DA) override {
2709 // Append a new link action for each device.
2710 unsigned I = 0;
2711 for (auto &LI : DeviceLinkerInputs) {
2712 auto *DeviceLinkAction =
2713 C.MakeAction<LinkJobAction>(LI, types::TY_Image);
2714 DA.add(*DeviceLinkAction, *ToolChains[0],
2715 CudaArchToString(GpuArchList[I]), AssociatedOffloadKind);
2716 ++I;
Samuel Antao64e965e2016-09-30 15:34:19 +00002717 }
Samuel Antao64e965e2016-09-30 15:34:19 +00002718 }
2719 };
2720
Samuel Antao28c4f182016-10-27 17:08:03 +00002721 /// OpenMP action builder. The host bitcode is passed to the device frontend
2722 /// and all the device linked images are passed to the host link phase.
2723 class OpenMPActionBuilder final : public DeviceActionBuilder {
2724 /// The OpenMP actions for the current input.
2725 ActionList OpenMPDeviceActions;
2726
2727 /// The linker inputs obtained for each toolchain.
2728 SmallVector<ActionList, 8> DeviceLinkerInputs;
2729
2730 public:
2731 OpenMPActionBuilder(Compilation &C, DerivedArgList &Args,
2732 const Driver::InputList &Inputs)
2733 : DeviceActionBuilder(C, Args, Inputs, Action::OFK_OpenMP) {}
2734
2735 ActionBuilderReturnCode
2736 getDeviceDependences(OffloadAction::DeviceDependences &DA,
2737 phases::ID CurPhase, phases::ID FinalPhase,
2738 PhasesTy &Phases) override {
Alexey Bataeva5178f52018-09-28 16:17:59 +00002739 if (OpenMPDeviceActions.empty())
2740 return ABRT_Inactive;
Samuel Antao28c4f182016-10-27 17:08:03 +00002741
2742 // We should always have an action for each input.
2743 assert(OpenMPDeviceActions.size() == ToolChains.size() &&
2744 "Number of OpenMP actions and toolchains do not match.");
2745
2746 // The host only depends on device action in the linking phase, when all
2747 // the device images have to be embedded in the host image.
2748 if (CurPhase == phases::Link) {
2749 assert(ToolChains.size() == DeviceLinkerInputs.size() &&
2750 "Toolchains and linker inputs sizes do not match.");
2751 auto LI = DeviceLinkerInputs.begin();
2752 for (auto *A : OpenMPDeviceActions) {
2753 LI->push_back(A);
2754 ++LI;
2755 }
2756
2757 // We passed the device action as a host dependence, so we don't need to
2758 // do anything else with them.
2759 OpenMPDeviceActions.clear();
2760 return ABRT_Success;
2761 }
2762
2763 // By default, we produce an action for each device arch.
2764 for (Action *&A : OpenMPDeviceActions)
2765 A = C.getDriver().ConstructPhaseAction(C, Args, CurPhase, A);
2766
2767 return ABRT_Success;
2768 }
2769
2770 ActionBuilderReturnCode addDeviceDepences(Action *HostAction) override {
2771
2772 // If this is an input action replicate it for each OpenMP toolchain.
2773 if (auto *IA = dyn_cast<InputAction>(HostAction)) {
2774 OpenMPDeviceActions.clear();
2775 for (unsigned I = 0; I < ToolChains.size(); ++I)
2776 OpenMPDeviceActions.push_back(
2777 C.MakeAction<InputAction>(IA->getInputArg(), IA->getType()));
2778 return ABRT_Success;
2779 }
2780
Samuel Antaofab4f372016-10-27 18:00:51 +00002781 // If this is an unbundling action use it as is for each OpenMP toolchain.
2782 if (auto *UA = dyn_cast<OffloadUnbundlingJobAction>(HostAction)) {
2783 OpenMPDeviceActions.clear();
Alexey Bataeva5178f52018-09-28 16:17:59 +00002784 auto *IA = cast<InputAction>(UA->getInputs().back());
2785 std::string FileName = IA->getInputArg().getAsString(Args);
2786 // Check if the type of the file is the same as the action. Do not
2787 // unbundle it if it is not. Do not unbundle .so files, for example,
2788 // which are not object files.
2789 if (IA->getType() == types::TY_Object &&
2790 (!llvm::sys::path::has_extension(FileName) ||
2791 types::lookupTypeForExtension(
2792 llvm::sys::path::extension(FileName).drop_front()) !=
2793 types::TY_Object))
2794 return ABRT_Inactive;
Samuel Antaofab4f372016-10-27 18:00:51 +00002795 for (unsigned I = 0; I < ToolChains.size(); ++I) {
2796 OpenMPDeviceActions.push_back(UA);
2797 UA->registerDependentActionInfo(
2798 ToolChains[I], /*BoundArch=*/StringRef(), Action::OFK_OpenMP);
2799 }
2800 return ABRT_Success;
2801 }
2802
Samuel Antao28c4f182016-10-27 17:08:03 +00002803 // When generating code for OpenMP we use the host compile phase result as
2804 // a dependence to the device compile phase so that it can learn what
2805 // declarations should be emitted. However, this is not the only use for
2806 // the host action, so we prevent it from being collapsed.
2807 if (isa<CompileJobAction>(HostAction)) {
2808 HostAction->setCannotBeCollapsedWithNextDependentAction();
2809 assert(ToolChains.size() == OpenMPDeviceActions.size() &&
2810 "Toolchains and device action sizes do not match.");
2811 OffloadAction::HostDependence HDep(
2812 *HostAction, *C.getSingleOffloadToolChain<Action::OFK_Host>(),
2813 /*BoundArch=*/nullptr, Action::OFK_OpenMP);
2814 auto TC = ToolChains.begin();
2815 for (Action *&A : OpenMPDeviceActions) {
2816 assert(isa<CompileJobAction>(A));
2817 OffloadAction::DeviceDependences DDep;
2818 DDep.add(*A, **TC, /*BoundArch=*/nullptr, Action::OFK_OpenMP);
2819 A = C.MakeAction<OffloadAction>(HDep, DDep);
2820 ++TC;
2821 }
2822 }
2823 return ABRT_Success;
2824 }
2825
Samuel Antao69d6f312016-10-27 17:50:43 +00002826 void appendTopLevelActions(ActionList &AL) override {
2827 if (OpenMPDeviceActions.empty())
2828 return;
2829
2830 // We should always have an action for each input.
2831 assert(OpenMPDeviceActions.size() == ToolChains.size() &&
2832 "Number of OpenMP actions and toolchains do not match.");
2833
2834 // Append all device actions followed by the proper offload action.
2835 auto TI = ToolChains.begin();
2836 for (auto *A : OpenMPDeviceActions) {
2837 OffloadAction::DeviceDependences Dep;
2838 Dep.add(*A, **TI, /*BoundArch=*/nullptr, Action::OFK_OpenMP);
2839 AL.push_back(C.MakeAction<OffloadAction>(Dep, A->getType()));
2840 ++TI;
2841 }
2842 // We no longer need the action stored in this builder.
2843 OpenMPDeviceActions.clear();
2844 }
2845
Samuel Antao28c4f182016-10-27 17:08:03 +00002846 void appendLinkDependences(OffloadAction::DeviceDependences &DA) override {
2847 assert(ToolChains.size() == DeviceLinkerInputs.size() &&
2848 "Toolchains and linker inputs sizes do not match.");
2849
2850 // Append a new link action for each device.
2851 auto TC = ToolChains.begin();
2852 for (auto &LI : DeviceLinkerInputs) {
2853 auto *DeviceLinkAction =
2854 C.MakeAction<LinkJobAction>(LI, types::TY_Image);
2855 DA.add(*DeviceLinkAction, **TC, /*BoundArch=*/nullptr,
2856 Action::OFK_OpenMP);
2857 ++TC;
2858 }
2859 }
2860
2861 bool initialize() override {
2862 // Get the OpenMP toolchains. If we don't get any, the action builder will
2863 // know there is nothing to do related to OpenMP offloading.
2864 auto OpenMPTCRange = C.getOffloadToolChains<Action::OFK_OpenMP>();
2865 for (auto TI = OpenMPTCRange.first, TE = OpenMPTCRange.second; TI != TE;
2866 ++TI)
2867 ToolChains.push_back(TI->second);
2868
2869 DeviceLinkerInputs.resize(ToolChains.size());
2870 return false;
2871 }
Samuel Antao69d6f312016-10-27 17:50:43 +00002872
2873 bool canUseBundlerUnbundler() const override {
2874 // OpenMP should use bundled files whenever possible.
2875 return true;
2876 }
Samuel Antao28c4f182016-10-27 17:08:03 +00002877 };
2878
2879 ///
2880 /// TODO: Add the implementation for other specialized builders here.
2881 ///
Samuel Antao64e965e2016-09-30 15:34:19 +00002882
2883 /// Specialized builders being used by this offloading action builder.
2884 SmallVector<DeviceActionBuilder *, 4> SpecializedBuilders;
2885
Samuel Antao69d6f312016-10-27 17:50:43 +00002886 /// Flag set to true if all valid builders allow file bundling/unbundling.
2887 bool CanUseBundler;
2888
Samuel Antao64e965e2016-09-30 15:34:19 +00002889public:
2890 OffloadingActionBuilder(Compilation &C, DerivedArgList &Args,
2891 const Driver::InputList &Inputs)
Samuel Antao10e905c2016-10-27 01:08:58 +00002892 : C(C) {
Samuel Antao64e965e2016-09-30 15:34:19 +00002893 // Create a specialized builder for each device toolchain.
2894
2895 IsValid = true;
2896
2897 // Create a specialized builder for CUDA.
2898 SpecializedBuilders.push_back(new CudaActionBuilder(C, Args, Inputs));
2899
Yaxun Liu3af038b2018-05-30 00:49:10 +00002900 // Create a specialized builder for HIP.
2901 SpecializedBuilders.push_back(new HIPActionBuilder(C, Args, Inputs));
2902
Samuel Antao28c4f182016-10-27 17:08:03 +00002903 // Create a specialized builder for OpenMP.
2904 SpecializedBuilders.push_back(new OpenMPActionBuilder(C, Args, Inputs));
2905
Samuel Antao64e965e2016-09-30 15:34:19 +00002906 //
2907 // TODO: Build other specialized builders here.
2908 //
2909
Samuel Antao69d6f312016-10-27 17:50:43 +00002910 // Initialize all the builders, keeping track of errors. If all valid
2911 // builders agree that we can use bundling, set the flag to true.
2912 unsigned ValidBuilders = 0u;
2913 unsigned ValidBuildersSupportingBundling = 0u;
2914 for (auto *SB : SpecializedBuilders) {
Samuel Antao64e965e2016-09-30 15:34:19 +00002915 IsValid = IsValid && !SB->initialize();
Samuel Antao69d6f312016-10-27 17:50:43 +00002916
2917 // Update the counters if the builder is valid.
2918 if (SB->isValid()) {
2919 ++ValidBuilders;
2920 if (SB->canUseBundlerUnbundler())
2921 ++ValidBuildersSupportingBundling;
2922 }
2923 }
2924 CanUseBundler =
2925 ValidBuilders && ValidBuilders == ValidBuildersSupportingBundling;
Artem Belevichf981e30b2016-08-02 22:37:47 +00002926 }
Justin Lebardc3c5042016-04-19 02:27:07 +00002927
Samuel Antao64e965e2016-09-30 15:34:19 +00002928 ~OffloadingActionBuilder() {
2929 for (auto *SB : SpecializedBuilders)
2930 delete SB;
Samuel Antaod06239d2016-07-15 23:13:27 +00002931 }
Artem Belevich0ff05cd2015-07-13 23:27:56 +00002932
Samuel Antao64e965e2016-09-30 15:34:19 +00002933 /// Generate an action that adds device dependences (if any) to a host action.
2934 /// If no device dependence actions exist, just return the host action \a
2935 /// HostAction. If an error is found or if no builder requires the host action
2936 /// to be generated, return nullptr.
2937 Action *
2938 addDeviceDependencesToHostAction(Action *HostAction, const Arg *InputArg,
2939 phases::ID CurPhase, phases::ID FinalPhase,
2940 DeviceActionBuilder::PhasesTy &Phases) {
2941 if (!IsValid)
2942 return nullptr;
Justin Lebar7bf77982016-01-11 23:27:13 +00002943
Samuel Antao64e965e2016-09-30 15:34:19 +00002944 if (SpecializedBuilders.empty())
2945 return HostAction;
2946
2947 assert(HostAction && "Invalid host action!");
2948
2949 OffloadAction::DeviceDependences DDeps;
2950 // Check if all the programming models agree we should not emit the host
2951 // action. Also, keep track of the offloading kinds employed.
2952 auto &OffloadKind = InputArgToOffloadKindMap[InputArg];
2953 unsigned InactiveBuilders = 0u;
2954 unsigned IgnoringBuilders = 0u;
2955 for (auto *SB : SpecializedBuilders) {
2956 if (!SB->isValid()) {
2957 ++InactiveBuilders;
2958 continue;
2959 }
2960
Samuel Antao28c4f182016-10-27 17:08:03 +00002961 auto RetCode =
2962 SB->getDeviceDependences(DDeps, CurPhase, FinalPhase, Phases);
Samuel Antao64e965e2016-09-30 15:34:19 +00002963
2964 // If the builder explicitly says the host action should be ignored,
2965 // we need to increment the variable that tracks the builders that request
2966 // the host object to be ignored.
2967 if (RetCode == DeviceActionBuilder::ABRT_Ignore_Host)
2968 ++IgnoringBuilders;
2969
2970 // Unless the builder was inactive for this action, we have to record the
2971 // offload kind because the host will have to use it.
2972 if (RetCode != DeviceActionBuilder::ABRT_Inactive)
2973 OffloadKind |= SB->getAssociatedOffloadKind();
2974 }
2975
2976 // If all builders agree that the host object should be ignored, just return
2977 // nullptr.
2978 if (IgnoringBuilders &&
2979 SpecializedBuilders.size() == (InactiveBuilders + IgnoringBuilders))
2980 return nullptr;
2981
2982 if (DDeps.getActions().empty())
2983 return HostAction;
2984
2985 // We have dependences we need to bundle together. We use an offload action
2986 // for that.
2987 OffloadAction::HostDependence HDep(
2988 *HostAction, *C.getSingleOffloadToolChain<Action::OFK_Host>(),
2989 /*BoundArch=*/nullptr, DDeps);
2990 return C.MakeAction<OffloadAction>(HDep, DDeps);
Artem Belevich0ff05cd2015-07-13 23:27:56 +00002991 }
2992
Samuel Antao64e965e2016-09-30 15:34:19 +00002993 /// Generate an action that adds a host dependence to a device action. The
2994 /// results will be kept in this action builder. Return true if an error was
2995 /// found.
Samuel Antaofab4f372016-10-27 18:00:51 +00002996 bool addHostDependenceToDeviceActions(Action *&HostAction,
Samuel Antao64e965e2016-09-30 15:34:19 +00002997 const Arg *InputArg) {
2998 if (!IsValid)
2999 return true;
Artem Belevich0ff05cd2015-07-13 23:27:56 +00003000
Samuel Antaofab4f372016-10-27 18:00:51 +00003001 // If we are supporting bundling/unbundling and the current action is an
3002 // input action of non-source file, we replace the host action by the
3003 // unbundling action. The bundler tool has the logic to detect if an input
3004 // is a bundle or not and if the input is not a bundle it assumes it is a
3005 // host file. Therefore it is safe to create an unbundling action even if
3006 // the input is not a bundle.
3007 if (CanUseBundler && isa<InputAction>(HostAction) &&
3008 InputArg->getOption().getKind() == llvm::opt::Option::InputClass &&
3009 !types::isSrcFile(HostAction->getType())) {
3010 auto UnbundlingHostAction =
3011 C.MakeAction<OffloadUnbundlingJobAction>(HostAction);
3012 UnbundlingHostAction->registerDependentActionInfo(
3013 C.getSingleOffloadToolChain<Action::OFK_Host>(),
Yaxun Liuf37b50a2018-07-24 01:03:44 +00003014 /*BoundArch=*/StringRef(), Action::OFK_Host);
Samuel Antaofab4f372016-10-27 18:00:51 +00003015 HostAction = UnbundlingHostAction;
3016 }
3017
Samuel Antao64e965e2016-09-30 15:34:19 +00003018 assert(HostAction && "Invalid host action!");
Artem Belevich0ff05cd2015-07-13 23:27:56 +00003019
Samuel Antao64e965e2016-09-30 15:34:19 +00003020 // Register the offload kinds that are used.
3021 auto &OffloadKind = InputArgToOffloadKindMap[InputArg];
3022 for (auto *SB : SpecializedBuilders) {
3023 if (!SB->isValid())
3024 continue;
Artem Belevich0ff05cd2015-07-13 23:27:56 +00003025
Samuel Antao64e965e2016-09-30 15:34:19 +00003026 auto RetCode = SB->addDeviceDepences(HostAction);
Artem Belevich0ff05cd2015-07-13 23:27:56 +00003027
Samuel Antao64e965e2016-09-30 15:34:19 +00003028 // Host dependences for device actions are not compatible with that same
3029 // action being ignored.
3030 assert(RetCode != DeviceActionBuilder::ABRT_Ignore_Host &&
3031 "Host dependence not expected to be ignored.!");
Samuel Antaod06239d2016-07-15 23:13:27 +00003032
Samuel Antao64e965e2016-09-30 15:34:19 +00003033 // Unless the builder was inactive for this action, we have to record the
3034 // offload kind because the host will have to use it.
3035 if (RetCode != DeviceActionBuilder::ABRT_Inactive)
3036 OffloadKind |= SB->getAssociatedOffloadKind();
3037 }
Artem Belevich0ff05cd2015-07-13 23:27:56 +00003038
Alexey Bataeva5178f52018-09-28 16:17:59 +00003039 // Do not use unbundler if the Host does not depend on device action.
3040 if (OffloadKind == Action::OFK_None && CanUseBundler)
3041 if (auto *UA = dyn_cast<OffloadUnbundlingJobAction>(HostAction))
3042 HostAction = UA->getInputs().back();
3043
Samuel Antao64e965e2016-09-30 15:34:19 +00003044 return false;
3045 }
3046
Samuel Antao69d6f312016-10-27 17:50:43 +00003047 /// Add the offloading top level actions to the provided action list. This
3048 /// function can replace the host action by a bundling action if the
3049 /// programming models allow it.
Samuel Antao64e965e2016-09-30 15:34:19 +00003050 bool appendTopLevelActions(ActionList &AL, Action *HostAction,
3051 const Arg *InputArg) {
Samuel Antao69d6f312016-10-27 17:50:43 +00003052 // Get the device actions to be appended.
3053 ActionList OffloadAL;
Samuel Antao64e965e2016-09-30 15:34:19 +00003054 for (auto *SB : SpecializedBuilders) {
3055 if (!SB->isValid())
3056 continue;
Samuel Antao69d6f312016-10-27 17:50:43 +00003057 SB->appendTopLevelActions(OffloadAL);
Samuel Antao64e965e2016-09-30 15:34:19 +00003058 }
3059
Samuel Antao69d6f312016-10-27 17:50:43 +00003060 // If we can use the bundler, replace the host action by the bundling one in
Yaxun Liu2bcc9512018-11-14 04:47:31 +00003061 // the resulting list. Otherwise, just append the device actions. For
3062 // device only compilation, HostAction is a null pointer, therefore only do
3063 // this when HostAction is not a null pointer.
3064 if (CanUseBundler && HostAction && !OffloadAL.empty()) {
Samuel Antao69d6f312016-10-27 17:50:43 +00003065 // Add the host action to the list in order to create the bundling action.
3066 OffloadAL.push_back(HostAction);
3067
3068 // We expect that the host action was just appended to the action list
3069 // before this method was called.
3070 assert(HostAction == AL.back() && "Host action not in the list??");
3071 HostAction = C.MakeAction<OffloadBundlingJobAction>(OffloadAL);
3072 AL.back() = HostAction;
3073 } else
3074 AL.append(OffloadAL.begin(), OffloadAL.end());
3075
Samuel Antao64e965e2016-09-30 15:34:19 +00003076 // Propagate to the current host action (if any) the offload information
3077 // associated with the current input.
3078 if (HostAction)
3079 HostAction->propagateHostOffloadInfo(InputArgToOffloadKindMap[InputArg],
3080 /*BoundArch=*/nullptr);
Samuel Antao64e965e2016-09-30 15:34:19 +00003081 return false;
Artem Belevich0ff05cd2015-07-13 23:27:56 +00003082 }
Artem Belevich5bde4e02015-07-20 20:02:54 +00003083
Samuel Antao64e965e2016-09-30 15:34:19 +00003084 /// Processes the host linker action. This currently consists of replacing it
3085 /// with an offload action if there are device link objects and propagate to
3086 /// the host action all the offload kinds used in the current compilation. The
3087 /// resulting action is returned.
3088 Action *processHostLinkAction(Action *HostAction) {
3089 // Add all the dependences from the device linking actions.
3090 OffloadAction::DeviceDependences DDeps;
3091 for (auto *SB : SpecializedBuilders) {
3092 if (!SB->isValid())
3093 continue;
Justin Lebar21e5d4f2016-01-14 21:41:27 +00003094
Samuel Antao64e965e2016-09-30 15:34:19 +00003095 SB->appendLinkDependences(DDeps);
Justin Lebar21e5d4f2016-01-14 21:41:27 +00003096 }
Samuel Antaod06239d2016-07-15 23:13:27 +00003097
Samuel Antao64e965e2016-09-30 15:34:19 +00003098 // Calculate all the offload kinds used in the current compilation.
3099 unsigned ActiveOffloadKinds = 0u;
3100 for (auto &I : InputArgToOffloadKindMap)
3101 ActiveOffloadKinds |= I.second;
3102
3103 // If we don't have device dependencies, we don't have to create an offload
3104 // action.
3105 if (DDeps.getActions().empty()) {
3106 // Propagate all the active kinds to host action. Given that it is a link
3107 // action it is assumed to depend on all actions generated so far.
3108 HostAction->propagateHostOffloadInfo(ActiveOffloadKinds,
3109 /*BoundArch=*/nullptr);
3110 return HostAction;
3111 }
3112
3113 // Create the offload action with all dependences. When an offload action
3114 // is created the kinds are propagated to the host action, so we don't have
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00003115 // to do that explicitly here.
Samuel Antao64e965e2016-09-30 15:34:19 +00003116 OffloadAction::HostDependence HDep(
3117 *HostAction, *C.getSingleOffloadToolChain<Action::OFK_Host>(),
3118 /*BoundArch*/ nullptr, ActiveOffloadKinds);
3119 return C.MakeAction<OffloadAction>(HDep, DDeps);
3120 }
3121};
3122} // anonymous namespace.
Artem Belevich0ff05cd2015-07-13 23:27:56 +00003123
Justin Lebar0f3474c2016-02-11 02:00:50 +00003124void Driver::BuildActions(Compilation &C, DerivedArgList &Args,
3125 const InputList &Inputs, ActionList &Actions) const {
Chad Rosierecdede82011-08-12 22:08:57 +00003126 llvm::PrettyStackTraceString CrashInfo("Building compilation actions");
Joerg Sonnenbergerb86f5f42011-03-06 23:31:01 +00003127
Daniel Dunbar34c41872009-03-13 00:17:48 +00003128 if (!SuppressMissingInputWarning && Inputs.empty()) {
Daniel Dunbarbfeec742009-03-12 23:55:14 +00003129 Diag(clang::diag::err_drv_no_input_files);
3130 return;
3131 }
3132
Chad Rosier7742b5d2011-07-27 23:36:45 +00003133 Arg *FinalPhaseArg;
3134 phases::ID FinalPhase = getFinalPhase(Args, &FinalPhaseArg);
Daniel Dunbarbfeec742009-03-12 23:55:14 +00003135
Bob Haarmanaaf51912017-02-27 19:40:19 +00003136 if (FinalPhase == phases::Link) {
3137 if (Args.hasArg(options::OPT_emit_llvm))
3138 Diag(clang::diag::err_drv_emit_llvm_link);
3139 if (IsCLMode() && LTOMode != LTOK_None &&
3140 !Args.getLastArgValue(options::OPT_fuse_ld_EQ).equals_lower("lld"))
3141 Diag(clang::diag::err_drv_lto_without_lld);
Rafael Espindolae8025642013-08-25 14:27:09 +00003142 }
3143
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00003144 // Reject -Z* at the top level, these options should never have been exposed
3145 // by gcc.
Daniel Dunbardd765242009-03-26 16:12:09 +00003146 if (Arg *A = Args.getLastArg(options::OPT_Z_Joined))
Daniel Dunbar0e759942009-03-20 06:14:23 +00003147 Diag(clang::diag::err_drv_use_of_Z_option) << A->getAsString(Args);
Daniel Dunbarbfeec742009-03-12 23:55:14 +00003148
Hans Wennborg13b7fe72013-08-12 23:26:25 +00003149 // Diagnose misuse of /Fo.
3150 if (Arg *A = Args.getLastArg(options::OPT__SLASH_Fo)) {
Hans Wennborg13b7fe72013-08-12 23:26:25 +00003151 StringRef V = A->getValue();
Hans Wennborg61647532014-11-17 19:16:36 +00003152 if (Inputs.size() > 1 && !V.empty() &&
3153 !llvm::sys::path::is_separator(V.back())) {
Hans Wennborg13b7fe72013-08-12 23:26:25 +00003154 // Check whether /Fo tries to name an output file for multiple inputs.
Hans Wennborg9c1659b2013-10-18 22:49:04 +00003155 Diag(clang::diag::err_drv_out_file_argument_with_multiple_sources)
Douglas Katzmana67e50c2015-06-26 15:47:46 +00003156 << A->getSpelling() << V;
Hans Wennborg13b7fe72013-08-12 23:26:25 +00003157 Args.eraseArg(options::OPT__SLASH_Fo);
3158 }
3159 }
3160
Hans Wennborg9c1659b2013-10-18 22:49:04 +00003161 // Diagnose misuse of /Fa.
3162 if (Arg *A = Args.getLastArg(options::OPT__SLASH_Fa)) {
3163 StringRef V = A->getValue();
Hans Wennborg61647532014-11-17 19:16:36 +00003164 if (Inputs.size() > 1 && !V.empty() &&
3165 !llvm::sys::path::is_separator(V.back())) {
Hans Wennborg9c1659b2013-10-18 22:49:04 +00003166 // Check whether /Fa tries to name an asm file for multiple inputs.
3167 Diag(clang::diag::err_drv_out_file_argument_with_multiple_sources)
Douglas Katzmana67e50c2015-06-26 15:47:46 +00003168 << A->getSpelling() << V;
Hans Wennborg9c1659b2013-10-18 22:49:04 +00003169 Args.eraseArg(options::OPT__SLASH_Fa);
3170 }
3171 }
3172
Ehsan Akhgari81f36b72014-09-11 18:16:21 +00003173 // Diagnose misuse of /o.
3174 if (Arg *A = Args.getLastArg(options::OPT__SLASH_o)) {
3175 if (A->getValue()[0] == '\0') {
3176 // It has to have a value.
3177 Diag(clang::diag::err_drv_missing_argument) << A->getSpelling() << 1;
3178 Args.eraseArg(options::OPT__SLASH_o);
3179 }
3180 }
3181
Mike Rice58df1af2018-09-11 17:10:44 +00003182 // Ignore /Yc/Yu if both /Yc and /Yu passed but with different filenames.
Nico Weber2ca4be92016-03-01 23:16:44 +00003183 Arg *YcArg = Args.getLastArg(options::OPT__SLASH_Yc);
3184 Arg *YuArg = Args.getLastArg(options::OPT__SLASH_Yu);
Nico Weber2ca4be92016-03-01 23:16:44 +00003185 if (YcArg && YuArg && strcmp(YcArg->getValue(), YuArg->getValue()) != 0) {
3186 Diag(clang::diag::warn_drv_ycyu_different_arg_clang_cl);
3187 Args.eraseArg(options::OPT__SLASH_Yc);
3188 Args.eraseArg(options::OPT__SLASH_Yu);
3189 YcArg = YuArg = nullptr;
3190 }
Nico Weber2ca4be92016-03-01 23:16:44 +00003191 if (YcArg && Inputs.size() > 1) {
3192 Diag(clang::diag::warn_drv_yc_multiple_inputs_clang_cl);
3193 Args.eraseArg(options::OPT__SLASH_Yc);
3194 YcArg = nullptr;
3195 }
Erich Keaneeaca3882018-08-17 13:43:39 +00003196 if (FinalPhase == phases::Preprocess || Args.hasArg(options::OPT__SLASH_Y_)) {
3197 // If only preprocessing or /Y- is used, all pch handling is disabled.
3198 // Rather than check for it everywhere, just remove clang-cl pch-related
3199 // flags here.
Nico Weber2ca4be92016-03-01 23:16:44 +00003200 Args.eraseArg(options::OPT__SLASH_Fp);
3201 Args.eraseArg(options::OPT__SLASH_Yc);
3202 Args.eraseArg(options::OPT__SLASH_Yu);
3203 YcArg = YuArg = nullptr;
3204 }
Nico Weber2ca4be92016-03-01 23:16:44 +00003205
Samuel Antao64e965e2016-09-30 15:34:19 +00003206 // Builder to be used to build offloading actions.
3207 OffloadingActionBuilder OffloadBuilder(C, Args, Inputs);
Samuel Antaod06239d2016-07-15 23:13:27 +00003208
Daniel Dunbar65229332009-03-13 11:38:42 +00003209 // Construct the actions to perform.
Richard Smithcd35eff2018-09-15 01:21:16 +00003210 HeaderModulePrecompileJobAction *HeaderModuleAction = nullptr;
Daniel Dunbar65229332009-03-13 11:38:42 +00003211 ActionList LinkerInputs;
Alp Toker965f8822013-11-27 05:22:15 +00003212
Matthew Curtis7ab8b2b2013-03-07 12:32:26 +00003213 llvm::SmallVector<phases::ID, phases::MaxNumberOfPhases> PL;
Artem Belevich5bde4e02015-07-20 20:02:54 +00003214 for (auto &I : Inputs) {
3215 types::ID InputType = I.first;
3216 const Arg *InputArg = I.second;
Daniel Dunbar65229332009-03-13 11:38:42 +00003217
Matthew Curtis7ab8b2b2013-03-07 12:32:26 +00003218 PL.clear();
3219 types::getCompilationPhases(InputType, PL);
Daniel Dunbar65229332009-03-13 11:38:42 +00003220
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00003221 // If the first step comes after the final phase we are doing as part of
3222 // this compilation, warn the user about it.
Matthew Curtis7ab8b2b2013-03-07 12:32:26 +00003223 phases::ID InitialPhase = PL[0];
Daniel Dunbar65229332009-03-13 11:38:42 +00003224 if (InitialPhase > FinalPhase) {
Martin Storsjo665c7a42018-05-04 06:05:58 +00003225 if (InputArg->isClaimed())
3226 continue;
3227
Daniel Dunbaradc5c7c2009-03-19 07:57:08 +00003228 // Claim here to avoid the more general unused warning.
3229 InputArg->claim();
Daniel Dunbar07806ca2009-09-17 04:13:26 +00003230
Daniel Dunbar2db3e732011-04-20 15:44:48 +00003231 // Suppress all unused style warnings with -Qunused-arguments
3232 if (Args.hasArg(options::OPT_Qunused_arguments))
3233 continue;
3234
Richard Smith403f76e2012-08-06 04:09:06 +00003235 // Special case when final phase determined by binary name, rather than
3236 // by a command-line argument with a corresponding Arg.
Hans Wennborg70850d82013-07-18 20:29:38 +00003237 if (CCCIsCPP())
Richard Smith403f76e2012-08-06 04:09:06 +00003238 Diag(clang::diag::warn_drv_input_file_unused_by_cpp)
Douglas Katzmana67e50c2015-06-26 15:47:46 +00003239 << InputArg->getAsString(Args) << getPhaseName(InitialPhase);
Daniel Dunbar07806ca2009-09-17 04:13:26 +00003240 // Special case '-E' warning on a previously preprocessed file to make
3241 // more sense.
Richard Smith403f76e2012-08-06 04:09:06 +00003242 else if (InitialPhase == phases::Compile &&
3243 FinalPhase == phases::Preprocess &&
3244 getPreprocessedType(InputType) == types::TY_INVALID)
Daniel Dunbar07806ca2009-09-17 04:13:26 +00003245 Diag(clang::diag::warn_drv_preprocessed_input_file_unused)
Douglas Katzmana67e50c2015-06-26 15:47:46 +00003246 << InputArg->getAsString(Args) << !!FinalPhaseArg
3247 << (FinalPhaseArg ? FinalPhaseArg->getOption().getName() : "");
Daniel Dunbar07806ca2009-09-17 04:13:26 +00003248 else
3249 Diag(clang::diag::warn_drv_input_file_unused)
Douglas Katzmana67e50c2015-06-26 15:47:46 +00003250 << InputArg->getAsString(Args) << getPhaseName(InitialPhase)
3251 << !!FinalPhaseArg
3252 << (FinalPhaseArg ? FinalPhaseArg->getOption().getName() : "");
Daniel Dunbar65229332009-03-13 11:38:42 +00003253 continue;
3254 }
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00003255
Nico Weberad2d8f32016-04-21 19:59:10 +00003256 if (YcArg) {
3257 // Add a separate precompile phase for the compile phase.
3258 if (FinalPhase >= phases::Compile) {
Richard Smith8cd452d2016-08-30 18:55:16 +00003259 const types::ID HeaderType = lookupHeaderTypeForSourceType(InputType);
Nico Weberad2d8f32016-04-21 19:59:10 +00003260 llvm::SmallVector<phases::ID, phases::MaxNumberOfPhases> PCHPL;
Richard Smith8cd452d2016-08-30 18:55:16 +00003261 types::getCompilationPhases(HeaderType, PCHPL);
Nico Weberad2d8f32016-04-21 19:59:10 +00003262 // Build the pipeline for the pch file.
Richard Smith8cd452d2016-08-30 18:55:16 +00003263 Action *ClangClPch =
Erich Keane76675de2018-07-05 17:22:13 +00003264 C.MakeAction<InputAction>(*InputArg, HeaderType);
Nico Weberad2d8f32016-04-21 19:59:10 +00003265 for (phases::ID Phase : PCHPL)
3266 ClangClPch = ConstructPhaseAction(C, Args, Phase, ClangClPch);
3267 assert(ClangClPch);
3268 Actions.push_back(ClangClPch);
3269 // The driver currently exits after the first failed command. This
3270 // relies on that behavior, to make sure if the pch generation fails,
3271 // the main compilation won't run.
Hans Wennborg08c5a7b2018-06-25 13:23:49 +00003272 // FIXME: If the main compilation fails, the PCH generation should
3273 // probably not be considered successful either.
Nico Weberad2d8f32016-04-21 19:59:10 +00003274 }
3275 }
3276
Daniel Dunbar65229332009-03-13 11:38:42 +00003277 // Build the pipeline for this file.
Justin Lebar41094612016-01-11 23:07:27 +00003278 Action *Current = C.MakeAction<InputAction>(*InputArg, InputType);
Samuel Antao64e965e2016-09-30 15:34:19 +00003279
3280 // Use the current host action in any of the offloading actions, if
3281 // required.
3282 if (OffloadBuilder.addHostDependenceToDeviceActions(Current, InputArg))
3283 break;
3284
Douglas Katzmana67e50c2015-06-26 15:47:46 +00003285 for (SmallVectorImpl<phases::ID>::iterator i = PL.begin(), e = PL.end();
3286 i != e; ++i) {
Matthew Curtis7ab8b2b2013-03-07 12:32:26 +00003287 phases::ID Phase = *i;
Daniel Dunbar65229332009-03-13 11:38:42 +00003288
3289 // We are done if this step is past what the user requested.
3290 if (Phase > FinalPhase)
3291 break;
3292
Samuel Antao64e965e2016-09-30 15:34:19 +00003293 // Add any offload action the host action depends on.
3294 Current = OffloadBuilder.addDeviceDependencesToHostAction(
3295 Current, InputArg, Phase, FinalPhase, PL);
3296 if (!Current)
3297 break;
3298
Daniel Dunbar65229332009-03-13 11:38:42 +00003299 // Queue linker inputs.
3300 if (Phase == phases::Link) {
Matthew Curtis7ab8b2b2013-03-07 12:32:26 +00003301 assert((i + 1) == e && "linking must be final compilation step.");
Justin Lebar41094612016-01-11 23:07:27 +00003302 LinkerInputs.push_back(Current);
3303 Current = nullptr;
Daniel Dunbar65229332009-03-13 11:38:42 +00003304 break;
3305 }
3306
Richard Smithcd35eff2018-09-15 01:21:16 +00003307 // Each precompiled header file after a module file action is a module
3308 // header of that same module file, rather than being compiled to a
3309 // separate PCH.
3310 if (Phase == phases::Precompile && HeaderModuleAction &&
3311 getPrecompiledType(InputType) == types::TY_PCH) {
3312 HeaderModuleAction->addModuleHeaderInput(Current);
3313 Current = nullptr;
3314 break;
3315 }
3316
3317 // FIXME: Should we include any prior module file outputs as inputs of
3318 // later actions in the same command line?
3319
Samuel Antao64e965e2016-09-30 15:34:19 +00003320 // Otherwise construct the appropriate action.
Richard Smithcd35eff2018-09-15 01:21:16 +00003321 Action *NewCurrent = ConstructPhaseAction(C, Args, Phase, Current);
Samuel Antao64e965e2016-09-30 15:34:19 +00003322
3323 // We didn't create a new action, so we will just move to the next phase.
3324 if (NewCurrent == Current)
Daniel Dunbar13864952009-03-24 20:17:30 +00003325 continue;
3326
Richard Smithcd35eff2018-09-15 01:21:16 +00003327 if (auto *HMA = dyn_cast<HeaderModulePrecompileJobAction>(NewCurrent))
3328 HeaderModuleAction = HMA;
3329
Samuel Antao64e965e2016-09-30 15:34:19 +00003330 Current = NewCurrent;
Artem Belevich0ff05cd2015-07-13 23:27:56 +00003331
Samuel Antao64e965e2016-09-30 15:34:19 +00003332 // Use the current host action in any of the offloading actions, if
3333 // required.
3334 if (OffloadBuilder.addHostDependenceToDeviceActions(Current, InputArg))
3335 break;
Artem Belevich0ff05cd2015-07-13 23:27:56 +00003336
Daniel Dunbar65229332009-03-13 11:38:42 +00003337 if (Current->getType() == types::TY_Nothing)
3338 break;
3339 }
3340
Samuel Antao64e965e2016-09-30 15:34:19 +00003341 // If we ended with something, add to the output list.
3342 if (Current)
Justin Lebar41094612016-01-11 23:07:27 +00003343 Actions.push_back(Current);
Samuel Antao64e965e2016-09-30 15:34:19 +00003344
3345 // Add any top level actions generated for offloading.
3346 OffloadBuilder.appendTopLevelActions(Actions, Current, InputArg);
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00003347 }
Daniel Dunbar65229332009-03-13 11:38:42 +00003348
Samuel Antao64e965e2016-09-30 15:34:19 +00003349 // Add a link action if necessary.
Samuel Antaod06239d2016-07-15 23:13:27 +00003350 if (!LinkerInputs.empty()) {
Samuel Antao64e965e2016-09-30 15:34:19 +00003351 Action *LA = C.MakeAction<LinkJobAction>(LinkerInputs, types::TY_Image);
3352 LA = OffloadBuilder.processHostLinkAction(LA);
3353 Actions.push_back(LA);
Samuel Antaod06239d2016-07-15 23:13:27 +00003354 }
Daniel Dunbarc7a67b72009-12-22 23:19:32 +00003355
3356 // If we are linking, claim any options which are obviously only used for
3357 // compilation.
Hans Wennborga8ef14f2013-09-17 00:03:41 +00003358 if (FinalPhase == phases::Link && PL.size() == 1) {
Daniel Dunbarc7a67b72009-12-22 23:19:32 +00003359 Args.ClaimAllArgs(options::OPT_CompileOnly_Group);
Hans Wennborga8ef14f2013-09-17 00:03:41 +00003360 Args.ClaimAllArgs(options::OPT_cl_compile_Group);
3361 }
3362
3363 // Claim ignored clang-cl options.
3364 Args.ClaimAllArgs(options::OPT_cl_ignored_Group);
Artem Belevichbaae0932015-07-28 21:01:30 +00003365
Justin Lebardc3c5042016-04-19 02:27:07 +00003366 // Claim --cuda-host-only and --cuda-compile-host-device, which may be passed
3367 // to non-CUDA compilations and should not trigger warnings there.
Artem Belevichbaae0932015-07-28 21:01:30 +00003368 Args.ClaimAllArgs(options::OPT_cuda_host_only);
Justin Lebardc3c5042016-04-19 02:27:07 +00003369 Args.ClaimAllArgs(options::OPT_cuda_compile_host_device);
Daniel Dunbar65229332009-03-13 11:38:42 +00003370}
3371
Artem Belevichecb178b2018-03-21 22:22:59 +00003372Action *Driver::ConstructPhaseAction(
3373 Compilation &C, const ArgList &Args, phases::ID Phase, Action *Input,
3374 Action::OffloadKind TargetDeviceOffloadKind) const {
Daniel Dunbar2608c542009-03-18 01:38:48 +00003375 llvm::PrettyStackTraceString CrashInfo("Constructing phase actions");
Samuel Antao64e965e2016-09-30 15:34:19 +00003376
3377 // Some types skip the assembler phase (e.g., llvm-bc), but we can't
3378 // encode this in the steps because the intermediate type depends on
3379 // arguments. Just special case here.
3380 if (Phase == phases::Assemble && Input->getType() != types::TY_PP_Asm)
3381 return Input;
3382
Daniel Dunbar65229332009-03-13 11:38:42 +00003383 // Build the appropriate action.
3384 switch (Phase) {
Douglas Katzmana67e50c2015-06-26 15:47:46 +00003385 case phases::Link:
3386 llvm_unreachable("link action invalid here.");
Daniel Dunbar65229332009-03-13 11:38:42 +00003387 case phases::Preprocess: {
Daniel Dunbard67a3222009-03-30 06:36:42 +00003388 types::ID OutputTy;
3389 // -{M, MM} alter the output type.
Daniel Dunbar86aed7d2010-12-08 21:33:40 +00003390 if (Args.hasArg(options::OPT_M, options::OPT_MM)) {
Daniel Dunbard67a3222009-03-30 06:36:42 +00003391 OutputTy = types::TY_Dependencies;
3392 } else {
David Blaikie5d577a22012-06-29 22:03:56 +00003393 OutputTy = Input->getType();
3394 if (!Args.hasFlag(options::OPT_frewrite_includes,
Justin Bognerce8245b2014-06-24 08:01:01 +00003395 options::OPT_fno_rewrite_includes, false) &&
Richard Smith86a3ef52017-06-09 21:24:02 +00003396 !Args.hasFlag(options::OPT_frewrite_imports,
3397 options::OPT_fno_rewrite_imports, false) &&
Justin Bognerce8245b2014-06-24 08:01:01 +00003398 !CCGenDiagnostics)
David Blaikie5d577a22012-06-29 22:03:56 +00003399 OutputTy = types::getPreprocessedType(OutputTy);
Daniel Dunbard67a3222009-03-30 06:36:42 +00003400 assert(OutputTy != types::TY_INVALID &&
3401 "Cannot preprocess this input type!");
3402 }
Justin Lebar41094612016-01-11 23:07:27 +00003403 return C.MakeAction<PreprocessJobAction>(Input, OutputTy);
Daniel Dunbar65229332009-03-13 11:38:42 +00003404 }
Aaron Ballman1f10cc52012-07-31 01:21:00 +00003405 case phases::Precompile: {
Richard Smithdd4ad3d2016-08-30 19:06:26 +00003406 types::ID OutputTy = getPrecompiledType(Input->getType());
3407 assert(OutputTy != types::TY_INVALID &&
3408 "Cannot precompile this input type!");
Richard Smithcd35eff2018-09-15 01:21:16 +00003409
3410 // If we're given a module name, precompile header file inputs as a
3411 // module, not as a precompiled header.
3412 const char *ModName = nullptr;
3413 if (OutputTy == types::TY_PCH) {
3414 if (Arg *A = Args.getLastArg(options::OPT_fmodule_name_EQ))
3415 ModName = A->getValue();
3416 if (ModName)
3417 OutputTy = types::TY_ModuleFile;
3418 }
3419
Aaron Ballman1f10cc52012-07-31 01:21:00 +00003420 if (Args.hasArg(options::OPT_fsyntax_only)) {
3421 // Syntax checks should not emit a PCH file
3422 OutputTy = types::TY_Nothing;
3423 }
Richard Smithcd35eff2018-09-15 01:21:16 +00003424
3425 if (ModName)
3426 return C.MakeAction<HeaderModulePrecompileJobAction>(Input, OutputTy,
3427 ModName);
Justin Lebar41094612016-01-11 23:07:27 +00003428 return C.MakeAction<PrecompileJobAction>(Input, OutputTy);
Aaron Ballman1f10cc52012-07-31 01:21:00 +00003429 }
Daniel Dunbar65229332009-03-13 11:38:42 +00003430 case phases::Compile: {
David Blaikie486f4402014-08-29 07:25:23 +00003431 if (Args.hasArg(options::OPT_fsyntax_only))
Justin Lebar41094612016-01-11 23:07:27 +00003432 return C.MakeAction<CompileJobAction>(Input, types::TY_Nothing);
David Blaikie486f4402014-08-29 07:25:23 +00003433 if (Args.hasArg(options::OPT_rewrite_objc))
Justin Lebar41094612016-01-11 23:07:27 +00003434 return C.MakeAction<CompileJobAction>(Input, types::TY_RewrittenObjC);
David Blaikie486f4402014-08-29 07:25:23 +00003435 if (Args.hasArg(options::OPT_rewrite_legacy_objc))
Justin Lebar41094612016-01-11 23:07:27 +00003436 return C.MakeAction<CompileJobAction>(Input,
3437 types::TY_RewrittenLegacyObjC);
David Blaikie486f4402014-08-29 07:25:23 +00003438 if (Args.hasArg(options::OPT__analyze, options::OPT__analyze_auto))
Justin Lebar41094612016-01-11 23:07:27 +00003439 return C.MakeAction<AnalyzeJobAction>(Input, types::TY_Plist);
David Blaikie486f4402014-08-29 07:25:23 +00003440 if (Args.hasArg(options::OPT__migrate))
Justin Lebar41094612016-01-11 23:07:27 +00003441 return C.MakeAction<MigrateJobAction>(Input, types::TY_Remap);
David Blaikie486f4402014-08-29 07:25:23 +00003442 if (Args.hasArg(options::OPT_emit_ast))
Justin Lebar41094612016-01-11 23:07:27 +00003443 return C.MakeAction<CompileJobAction>(Input, types::TY_AST);
David Blaikie486f4402014-08-29 07:25:23 +00003444 if (Args.hasArg(options::OPT_module_file_info))
Justin Lebar41094612016-01-11 23:07:27 +00003445 return C.MakeAction<CompileJobAction>(Input, types::TY_ModuleFile);
David Blaikie486f4402014-08-29 07:25:23 +00003446 if (Args.hasArg(options::OPT_verify_pch))
Justin Lebar41094612016-01-11 23:07:27 +00003447 return C.MakeAction<VerifyPCHJobAction>(Input, types::TY_Nothing);
3448 return C.MakeAction<CompileJobAction>(Input, types::TY_LLVM_BC);
Bob Wilson23a55f12014-12-21 07:00:00 +00003449 }
3450 case phases::Backend: {
Artem Belevichecb178b2018-03-21 22:22:59 +00003451 if (isUsingLTO() && TargetDeviceOffloadKind == Action::OFK_None) {
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00003452 types::ID Output =
Douglas Katzmana67e50c2015-06-26 15:47:46 +00003453 Args.hasArg(options::OPT_S) ? types::TY_LTO_IR : types::TY_LTO_BC;
Justin Lebar41094612016-01-11 23:07:27 +00003454 return C.MakeAction<BackendJobAction>(Input, Output);
David Blaikie486f4402014-08-29 07:25:23 +00003455 }
3456 if (Args.hasArg(options::OPT_emit_llvm)) {
Shuxin Yang4b3c7ff2013-08-23 21:34:57 +00003457 types::ID Output =
Douglas Katzmana67e50c2015-06-26 15:47:46 +00003458 Args.hasArg(options::OPT_S) ? types::TY_LLVM_IR : types::TY_LLVM_BC;
Justin Lebar41094612016-01-11 23:07:27 +00003459 return C.MakeAction<BackendJobAction>(Input, Output);
Daniel Dunbar65229332009-03-13 11:38:42 +00003460 }
Justin Lebar41094612016-01-11 23:07:27 +00003461 return C.MakeAction<BackendJobAction>(Input, types::TY_PP_Asm);
Daniel Dunbar65229332009-03-13 11:38:42 +00003462 }
3463 case phases::Assemble:
Justin Lebar21e5d4f2016-01-14 21:41:27 +00003464 return C.MakeAction<AssembleJobAction>(std::move(Input), types::TY_Object);
Daniel Dunbar65229332009-03-13 11:38:42 +00003465 }
3466
David Blaikie83d382b2011-09-23 05:06:16 +00003467 llvm_unreachable("invalid phase in ConstructPhaseAction");
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00003468}
3469
Daniel Dunbarf0eddb82009-03-18 02:55:38 +00003470void Driver::BuildJobs(Compilation &C) const {
Daniel Dunbar2608c542009-03-18 01:38:48 +00003471 llvm::PrettyStackTraceString CrashInfo("Building compilation jobs");
Daniel Dunbare75d8342009-03-16 06:56:51 +00003472
3473 Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o);
3474
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00003475 // It is an error to provide a -o option if we are making multiple output
3476 // files.
Daniel Dunbare75d8342009-03-16 06:56:51 +00003477 if (FinalOutput) {
3478 unsigned NumOutputs = 0;
Saleem Abdulrasoolda3f4e52014-12-29 21:02:47 +00003479 for (const Action *A : C.getActions())
3480 if (A->getType() != types::TY_Nothing)
Daniel Dunbare75d8342009-03-16 06:56:51 +00003481 ++NumOutputs;
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00003482
Daniel Dunbare75d8342009-03-16 06:56:51 +00003483 if (NumOutputs > 1) {
3484 Diag(clang::diag::err_drv_output_argument_with_multiple_files);
Craig Topper92fc2df2014-05-17 16:56:41 +00003485 FinalOutput = nullptr;
Daniel Dunbare75d8342009-03-16 06:56:51 +00003486 }
3487 }
3488
Chad Rosier35767232013-04-30 22:01:21 +00003489 // Collect the list of architectures.
3490 llvm::StringSet<> ArchNames;
Saleem Abdulrasool688b6bc2014-12-29 19:01:36 +00003491 if (C.getDefaultToolChain().getTriple().isOSBinFormatMachO())
3492 for (const Arg *A : C.getArgs())
Chad Rosier35767232013-04-30 22:01:21 +00003493 if (A->getOption().matches(options::OPT_arch))
3494 ArchNames.insert(A->getValue());
Chad Rosier35767232013-04-30 22:01:21 +00003495
Justin Lebarb44f6fe2016-01-14 21:41:21 +00003496 // Set of (Action, canonical ToolChain triple) pairs we've built jobs for.
3497 std::map<std::pair<const Action *, std::string>, InputInfo> CachedResults;
Saleem Abdulrasool688b6bc2014-12-29 19:01:36 +00003498 for (Action *A : C.getActions()) {
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00003499 // If we are linking an image for multiple archs then the linker wants
3500 // -arch_multiple and -final_output <final image name>. Unfortunately, this
3501 // doesn't fit in cleanly because we have to pass this information down.
Daniel Dunbare75d8342009-03-16 06:56:51 +00003502 //
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00003503 // FIXME: This is a hack; find a cleaner way to integrate this into the
3504 // process.
Craig Topper92fc2df2014-05-17 16:56:41 +00003505 const char *LinkingOutput = nullptr;
Daniel Dunbardd765242009-03-26 16:12:09 +00003506 if (isa<LipoJobAction>(A)) {
Daniel Dunbare75d8342009-03-16 06:56:51 +00003507 if (FinalOutput)
Richard Smithbd55daf2012-11-01 04:30:05 +00003508 LinkingOutput = FinalOutput->getValue();
Daniel Dunbare75d8342009-03-16 06:56:51 +00003509 else
Hans Wennborga7707222015-01-09 17:38:53 +00003510 LinkingOutput = getDefaultImageName();
Daniel Dunbare75d8342009-03-16 06:56:51 +00003511 }
3512
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00003513 BuildJobsForAction(C, A, &C.getDefaultToolChain(),
Mehdi Aminic50b1a22016-10-07 21:27:26 +00003514 /*BoundArch*/ StringRef(),
Daniel Dunbare75d8342009-03-16 06:56:51 +00003515 /*AtTopLevel*/ true,
Chad Rosier35767232013-04-30 22:01:21 +00003516 /*MultipleArchs*/ ArchNames.size() > 1,
Samuel Antaod06239d2016-07-15 23:13:27 +00003517 /*LinkingOutput*/ LinkingOutput, CachedResults,
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003518 /*TargetDeviceOffloadKind*/ Action::OFK_None);
Daniel Dunbare75d8342009-03-16 06:56:51 +00003519 }
Daniel Dunbar3ce436d2009-03-16 06:42:30 +00003520
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00003521 // If the user passed -Qunused-arguments or there were errors, don't warn
3522 // about any unused arguments.
Argyrios Kyrtzidis31448a42010-11-18 21:47:07 +00003523 if (Diags.hasErrorOccurred() ||
Daniel Dunbara3cfbe32009-04-07 19:04:18 +00003524 C.getArgs().hasArg(options::OPT_Qunused_arguments))
Daniel Dunbard175d972009-03-18 18:03:46 +00003525 return;
3526
Daniel Dunbar58399ae2009-03-29 22:24:54 +00003527 // Claim -### here.
Douglas Katzmana67e50c2015-06-26 15:47:46 +00003528 (void)C.getArgs().hasArg(options::OPT__HASH_HASH_HASH);
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00003529
Nico Weber47bf5052016-04-25 21:15:49 +00003530 // Claim --driver-mode, --rsp-quoting, it was handled earlier.
Douglas Katzmana67e50c2015-06-26 15:47:46 +00003531 (void)C.getArgs().hasArg(options::OPT_driver_mode);
Nico Weber47bf5052016-04-25 21:15:49 +00003532 (void)C.getArgs().hasArg(options::OPT_rsp_quoting);
Hans Wennborg70850d82013-07-18 20:29:38 +00003533
Saleem Abdulrasool688b6bc2014-12-29 19:01:36 +00003534 for (Arg *A : C.getArgs()) {
Daniel Dunbar3ce436d2009-03-16 06:42:30 +00003535 // FIXME: It would be nice to be able to send the argument to the
David Blaikie9c902b52011-09-25 23:23:43 +00003536 // DiagnosticsEngine, so that extra values, position, and so on could be
3537 // printed.
Daniel Dunbar90dd6f42009-04-04 00:52:26 +00003538 if (!A->isClaimed()) {
Michael J. Spencer66e2b202012-10-19 22:37:06 +00003539 if (A->getOption().hasFlag(options::NoArgumentUnused))
Daniel Dunbara3cfbe32009-04-07 19:04:18 +00003540 continue;
3541
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00003542 // Suppress the warning automatically if this is just a flag, and it is an
3543 // instance of an argument we already claimed.
Daniel Dunbar90dd6f42009-04-04 00:52:26 +00003544 const Option &Opt = A->getOption();
Michael J. Spencerad3ccc32012-08-20 21:41:17 +00003545 if (Opt.getKind() == Option::FlagClass) {
Daniel Dunbar90dd6f42009-04-04 00:52:26 +00003546 bool DuplicateClaimed = false;
3547
Sean Silva14facf32015-06-09 01:57:17 +00003548 for (const Arg *AA : C.getArgs().filtered(&Opt)) {
3549 if (AA->isClaimed()) {
Daniel Dunbar90dd6f42009-04-04 00:52:26 +00003550 DuplicateClaimed = true;
3551 break;
3552 }
3553 }
3554
3555 if (DuplicateClaimed)
3556 continue;
3557 }
3558
Ehsan Akhgarid8518332016-01-25 21:14:52 +00003559 // In clang-cl, don't mention unknown arguments here since they have
3560 // already been warned about.
3561 if (!IsCLMode() || !A->getOption().matches(options::OPT_UNKNOWN))
3562 Diag(clang::diag::warn_drv_unused_argument)
3563 << A->getAsString(C.getArgs());
Daniel Dunbar90dd6f42009-04-04 00:52:26 +00003564 }
Daniel Dunbar3ce436d2009-03-16 06:42:30 +00003565 }
Daniel Dunbar95e6b192009-03-13 22:12:33 +00003566}
Daniel Dunbarc4343942010-02-03 03:07:56 +00003567
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00003568namespace {
3569/// Utility class to control the collapse of dependent actions and select the
3570/// tools accordingly.
3571class ToolSelector final {
3572 /// The tool chain this selector refers to.
3573 const ToolChain &TC;
Daniel Dunbarf9ff3502010-05-14 02:03:00 +00003574
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00003575 /// The compilation this selector refers to.
3576 const Compilation &C;
Samuel Antaod06239d2016-07-15 23:13:27 +00003577
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00003578 /// The base action this selector refers to.
3579 const JobAction *BaseAction;
Samuel Antaod06239d2016-07-15 23:13:27 +00003580
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00003581 /// Set to true if the current toolchain refers to host actions.
3582 bool IsHostSelector;
Samuel Antaod06239d2016-07-15 23:13:27 +00003583
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00003584 /// Set to true if save-temps and embed-bitcode functionalities are active.
3585 bool SaveTemps;
3586 bool EmbedBitcode;
3587
3588 /// Get previous dependent action or null if that does not exist. If
3589 /// \a CanBeCollapsed is false, that action must be legal to collapse or
3590 /// null will be returned.
3591 const JobAction *getPrevDependentAction(const ActionList &Inputs,
3592 ActionList &SavedOffloadAction,
3593 bool CanBeCollapsed = true) {
3594 // An option can be collapsed only if it has a single input.
3595 if (Inputs.size() != 1)
Craig Topper92fc2df2014-05-17 16:56:41 +00003596 return nullptr;
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00003597
3598 Action *CurAction = *Inputs.begin();
3599 if (CanBeCollapsed &&
3600 !CurAction->isCollapsingWithNextDependentActionLegal())
3601 return nullptr;
3602
3603 // If the input action is an offload action. Look through it and save any
3604 // offload action that can be dropped in the event of a collapse.
3605 if (auto *OA = dyn_cast<OffloadAction>(CurAction)) {
3606 // If the dependent action is a device action, we will attempt to collapse
3607 // only with other device actions. Otherwise, we would do the same but
3608 // with host actions only.
3609 if (!IsHostSelector) {
3610 if (OA->hasSingleDeviceDependence(/*DoNotConsiderHostActions=*/true)) {
3611 CurAction =
3612 OA->getSingleDeviceDependence(/*DoNotConsiderHostActions=*/true);
3613 if (CanBeCollapsed &&
3614 !CurAction->isCollapsingWithNextDependentActionLegal())
3615 return nullptr;
3616 SavedOffloadAction.push_back(OA);
3617 return dyn_cast<JobAction>(CurAction);
3618 }
3619 } else if (OA->hasHostDependence()) {
3620 CurAction = OA->getHostDependence();
3621 if (CanBeCollapsed &&
3622 !CurAction->isCollapsingWithNextDependentActionLegal())
3623 return nullptr;
3624 SavedOffloadAction.push_back(OA);
3625 return dyn_cast<JobAction>(CurAction);
3626 }
3627 return nullptr;
3628 }
3629
3630 return dyn_cast<JobAction>(CurAction);
3631 }
3632
3633 /// Return true if an assemble action can be collapsed.
3634 bool canCollapseAssembleAction() const {
3635 return TC.useIntegratedAs() && !SaveTemps &&
3636 !C.getArgs().hasArg(options::OPT_via_file_asm) &&
3637 !C.getArgs().hasArg(options::OPT__SLASH_FA) &&
3638 !C.getArgs().hasArg(options::OPT__SLASH_Fa);
3639 }
3640
3641 /// Return true if a preprocessor action can be collapsed.
3642 bool canCollapsePreprocessorAction() const {
3643 return !C.getArgs().hasArg(options::OPT_no_integrated_cpp) &&
3644 !C.getArgs().hasArg(options::OPT_traditional_cpp) && !SaveTemps &&
3645 !C.getArgs().hasArg(options::OPT_rewrite_objc);
3646 }
3647
3648 /// Struct that relates an action with the offload actions that would be
3649 /// collapsed with it.
3650 struct JobActionInfo final {
3651 /// The action this info refers to.
3652 const JobAction *JA = nullptr;
3653 /// The offload actions we need to take care off if this action is
3654 /// collapsed.
3655 ActionList SavedOffloadAction;
3656 };
3657
3658 /// Append collapsed offload actions from the give nnumber of elements in the
3659 /// action info array.
3660 static void AppendCollapsedOffloadAction(ActionList &CollapsedOffloadAction,
3661 ArrayRef<JobActionInfo> &ActionInfo,
3662 unsigned ElementNum) {
3663 assert(ElementNum <= ActionInfo.size() && "Invalid number of elements.");
3664 for (unsigned I = 0; I < ElementNum; ++I)
3665 CollapsedOffloadAction.append(ActionInfo[I].SavedOffloadAction.begin(),
3666 ActionInfo[I].SavedOffloadAction.end());
3667 }
3668
3669 /// Functions that attempt to perform the combining. They detect if that is
3670 /// legal, and if so they update the inputs \a Inputs and the offload action
3671 /// that were collapsed in \a CollapsedOffloadAction. A tool that deals with
3672 /// the combined action is returned. If the combining is not legal or if the
3673 /// tool does not exist, null is returned.
3674 /// Currently three kinds of collapsing are supported:
3675 /// - Assemble + Backend + Compile;
3676 /// - Assemble + Backend ;
3677 /// - Backend + Compile.
3678 const Tool *
3679 combineAssembleBackendCompile(ArrayRef<JobActionInfo> ActionInfo,
Richard Smithcd35eff2018-09-15 01:21:16 +00003680 ActionList &Inputs,
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00003681 ActionList &CollapsedOffloadAction) {
3682 if (ActionInfo.size() < 3 || !canCollapseAssembleAction())
3683 return nullptr;
3684 auto *AJ = dyn_cast<AssembleJobAction>(ActionInfo[0].JA);
3685 auto *BJ = dyn_cast<BackendJobAction>(ActionInfo[1].JA);
3686 auto *CJ = dyn_cast<CompileJobAction>(ActionInfo[2].JA);
3687 if (!AJ || !BJ || !CJ)
3688 return nullptr;
3689
3690 // Get compiler tool.
3691 const Tool *T = TC.SelectTool(*CJ);
3692 if (!T)
3693 return nullptr;
3694
Steven Wu574b0f22016-03-01 01:07:58 +00003695 // When using -fembed-bitcode, it is required to have the same tool (clang)
3696 // for both CompilerJA and BackendJA. Otherwise, combine two stages.
3697 if (EmbedBitcode) {
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00003698 const Tool *BT = TC.SelectTool(*BJ);
3699 if (BT == T)
3700 return nullptr;
Steven Wu574b0f22016-03-01 01:07:58 +00003701 }
Bob Wilson23a55f12014-12-21 07:00:00 +00003702
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00003703 if (!T->hasIntegratedAssembler())
Bob Wilson23a55f12014-12-21 07:00:00 +00003704 return nullptr;
Samuel Antaod06239d2016-07-15 23:13:27 +00003705
Richard Smithcd35eff2018-09-15 01:21:16 +00003706 Inputs = CJ->getInputs();
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00003707 AppendCollapsedOffloadAction(CollapsedOffloadAction, ActionInfo,
3708 /*NumElements=*/3);
3709 return T;
3710 }
3711 const Tool *combineAssembleBackend(ArrayRef<JobActionInfo> ActionInfo,
Richard Smithcd35eff2018-09-15 01:21:16 +00003712 ActionList &Inputs,
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00003713 ActionList &CollapsedOffloadAction) {
3714 if (ActionInfo.size() < 2 || !canCollapseAssembleAction())
3715 return nullptr;
3716 auto *AJ = dyn_cast<AssembleJobAction>(ActionInfo[0].JA);
3717 auto *BJ = dyn_cast<BackendJobAction>(ActionInfo[1].JA);
3718 if (!AJ || !BJ)
3719 return nullptr;
3720
3721 // Retrieve the compile job, backend action must always be preceded by one.
3722 ActionList CompileJobOffloadActions;
3723 auto *CJ = getPrevDependentAction(BJ->getInputs(), CompileJobOffloadActions,
3724 /*CanBeCollapsed=*/false);
3725 if (!AJ || !BJ || !CJ)
3726 return nullptr;
3727
3728 assert(isa<CompileJobAction>(CJ) &&
3729 "Expecting compile job preceding backend job.");
3730
3731 // Get compiler tool.
3732 const Tool *T = TC.SelectTool(*CJ);
3733 if (!T)
3734 return nullptr;
3735
3736 if (!T->hasIntegratedAssembler())
3737 return nullptr;
3738
Richard Smithcd35eff2018-09-15 01:21:16 +00003739 Inputs = BJ->getInputs();
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00003740 AppendCollapsedOffloadAction(CollapsedOffloadAction, ActionInfo,
3741 /*NumElements=*/2);
3742 return T;
3743 }
3744 const Tool *combineBackendCompile(ArrayRef<JobActionInfo> ActionInfo,
Richard Smithcd35eff2018-09-15 01:21:16 +00003745 ActionList &Inputs,
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00003746 ActionList &CollapsedOffloadAction) {
Teresa Johnson9e4321c2018-04-17 16:39:25 +00003747 if (ActionInfo.size() < 2)
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00003748 return nullptr;
3749 auto *BJ = dyn_cast<BackendJobAction>(ActionInfo[0].JA);
3750 auto *CJ = dyn_cast<CompileJobAction>(ActionInfo[1].JA);
3751 if (!BJ || !CJ)
3752 return nullptr;
3753
Teresa Johnson9e4321c2018-04-17 16:39:25 +00003754 // Check if the initial input (to the compile job or its predessor if one
3755 // exists) is LLVM bitcode. In that case, no preprocessor step is required
3756 // and we can still collapse the compile and backend jobs when we have
3757 // -save-temps. I.e. there is no need for a separate compile job just to
3758 // emit unoptimized bitcode.
3759 bool InputIsBitcode = true;
3760 for (size_t i = 1; i < ActionInfo.size(); i++)
3761 if (ActionInfo[i].JA->getType() != types::TY_LLVM_BC &&
3762 ActionInfo[i].JA->getType() != types::TY_LTO_BC) {
3763 InputIsBitcode = false;
3764 break;
3765 }
3766 if (!InputIsBitcode && !canCollapsePreprocessorAction())
3767 return nullptr;
3768
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00003769 // Get compiler tool.
3770 const Tool *T = TC.SelectTool(*CJ);
3771 if (!T)
3772 return nullptr;
3773
Teresa Johnson9e4321c2018-04-17 16:39:25 +00003774 if (T->canEmitIR() && ((SaveTemps && !InputIsBitcode) || EmbedBitcode))
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00003775 return nullptr;
3776
Richard Smithcd35eff2018-09-15 01:21:16 +00003777 Inputs = CJ->getInputs();
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00003778 AppendCollapsedOffloadAction(CollapsedOffloadAction, ActionInfo,
3779 /*NumElements=*/2);
3780 return T;
3781 }
3782
3783 /// Updates the inputs if the obtained tool supports combining with
3784 /// preprocessor action, and the current input is indeed a preprocessor
3785 /// action. If combining results in the collapse of offloading actions, those
3786 /// are appended to \a CollapsedOffloadAction.
Richard Smithcd35eff2018-09-15 01:21:16 +00003787 void combineWithPreprocessor(const Tool *T, ActionList &Inputs,
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00003788 ActionList &CollapsedOffloadAction) {
3789 if (!T || !canCollapsePreprocessorAction() || !T->hasIntegratedCPP())
3790 return;
3791
3792 // Attempt to get a preprocessor action dependence.
3793 ActionList PreprocessJobOffloadActions;
Richard Smithcd35eff2018-09-15 01:21:16 +00003794 ActionList NewInputs;
3795 for (Action *A : Inputs) {
3796 auto *PJ = getPrevDependentAction({A}, PreprocessJobOffloadActions);
3797 if (!PJ || !isa<PreprocessJobAction>(PJ)) {
3798 NewInputs.push_back(A);
3799 continue;
3800 }
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00003801
Richard Smithcd35eff2018-09-15 01:21:16 +00003802 // This is legal to combine. Append any offload action we found and add the
3803 // current input to preprocessor inputs.
3804 CollapsedOffloadAction.append(PreprocessJobOffloadActions.begin(),
3805 PreprocessJobOffloadActions.end());
3806 NewInputs.append(PJ->input_begin(), PJ->input_end());
3807 }
3808 Inputs = NewInputs;
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00003809 }
3810
3811public:
3812 ToolSelector(const JobAction *BaseAction, const ToolChain &TC,
3813 const Compilation &C, bool SaveTemps, bool EmbedBitcode)
3814 : TC(TC), C(C), BaseAction(BaseAction), SaveTemps(SaveTemps),
3815 EmbedBitcode(EmbedBitcode) {
3816 assert(BaseAction && "Invalid base action.");
3817 IsHostSelector = BaseAction->getOffloadingDeviceKind() == Action::OFK_None;
3818 }
3819
3820 /// Check if a chain of actions can be combined and return the tool that can
3821 /// handle the combination of actions. The pointer to the current inputs \a
3822 /// Inputs and the list of offload actions \a CollapsedOffloadActions
3823 /// connected to collapsed actions are updated accordingly. The latter enables
3824 /// the caller of the selector to process them afterwards instead of just
3825 /// dropping them. If no suitable tool is found, null will be returned.
Richard Smithcd35eff2018-09-15 01:21:16 +00003826 const Tool *getTool(ActionList &Inputs,
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00003827 ActionList &CollapsedOffloadAction) {
3828 //
3829 // Get the largest chain of actions that we could combine.
3830 //
3831
3832 SmallVector<JobActionInfo, 5> ActionChain(1);
3833 ActionChain.back().JA = BaseAction;
3834 while (ActionChain.back().JA) {
3835 const Action *CurAction = ActionChain.back().JA;
3836
3837 // Grow the chain by one element.
3838 ActionChain.resize(ActionChain.size() + 1);
3839 JobActionInfo &AI = ActionChain.back();
3840
3841 // Attempt to fill it with the
3842 AI.JA =
3843 getPrevDependentAction(CurAction->getInputs(), AI.SavedOffloadAction);
Daniel Dunbarc4343942010-02-03 03:07:56 +00003844 }
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00003845
3846 // Pop the last action info as it could not be filled.
3847 ActionChain.pop_back();
3848
3849 //
3850 // Attempt to combine actions. If all combining attempts failed, just return
3851 // the tool of the provided action. At the end we attempt to combine the
3852 // action with any preprocessor action it may depend on.
3853 //
3854
3855 const Tool *T = combineAssembleBackendCompile(ActionChain, Inputs,
3856 CollapsedOffloadAction);
3857 if (!T)
3858 T = combineAssembleBackend(ActionChain, Inputs, CollapsedOffloadAction);
3859 if (!T)
3860 T = combineBackendCompile(ActionChain, Inputs, CollapsedOffloadAction);
3861 if (!T) {
Richard Smithcd35eff2018-09-15 01:21:16 +00003862 Inputs = BaseAction->getInputs();
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00003863 T = TC.SelectTool(*BaseAction);
3864 }
3865
3866 combineWithPreprocessor(T, Inputs, CollapsedOffloadAction);
3867 return T;
Daniel Dunbarc4343942010-02-03 03:07:56 +00003868 }
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00003869};
Daniel Dunbarc4343942010-02-03 03:07:56 +00003870}
3871
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003872/// Return a string that uniquely identifies the result of a job. The bound arch
3873/// is not necessarily represented in the toolchain's triple -- for example,
3874/// armv7 and armv7s both map to the same triple -- so we need both in our map.
3875/// Also, we need to add the offloading device kind, as the same tool chain can
3876/// be used for host and device for some programming models, e.g. OpenMP.
3877static std::string GetTriplePlusArchString(const ToolChain *TC,
3878 StringRef BoundArch,
3879 Action::OffloadKind OffloadKind) {
Justin Lebar55c83322016-01-16 03:30:08 +00003880 std::string TriplePlusArch = TC->getTriple().normalize();
Mehdi Aminic50b1a22016-10-07 21:27:26 +00003881 if (!BoundArch.empty()) {
Justin Lebar55c83322016-01-16 03:30:08 +00003882 TriplePlusArch += "-";
3883 TriplePlusArch += BoundArch;
3884 }
Samuel Antao59efaed2016-10-27 17:31:22 +00003885 TriplePlusArch += "-";
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003886 TriplePlusArch += Action::GetOffloadKindName(OffloadKind);
3887 return TriplePlusArch;
3888}
3889
3890InputInfo Driver::BuildJobsForAction(
3891 Compilation &C, const Action *A, const ToolChain *TC, StringRef BoundArch,
3892 bool AtTopLevel, bool MultipleArchs, const char *LinkingOutput,
3893 std::map<std::pair<const Action *, std::string>, InputInfo> &CachedResults,
3894 Action::OffloadKind TargetDeviceOffloadKind) const {
3895 std::pair<const Action *, std::string> ActionTC = {
3896 A, GetTriplePlusArchString(TC, BoundArch, TargetDeviceOffloadKind)};
Justin Lebarb44f6fe2016-01-14 21:41:21 +00003897 auto CachedResult = CachedResults.find(ActionTC);
3898 if (CachedResult != CachedResults.end()) {
3899 return CachedResult->second;
3900 }
Samuel Antaod06239d2016-07-15 23:13:27 +00003901 InputInfo Result = BuildJobsForActionNoCache(
3902 C, A, TC, BoundArch, AtTopLevel, MultipleArchs, LinkingOutput,
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003903 CachedResults, TargetDeviceOffloadKind);
Justin Lebarb44f6fe2016-01-14 21:41:21 +00003904 CachedResults[ActionTC] = Result;
3905 return Result;
3906}
3907
3908InputInfo Driver::BuildJobsForActionNoCache(
Mehdi Aminic50b1a22016-10-07 21:27:26 +00003909 Compilation &C, const Action *A, const ToolChain *TC, StringRef BoundArch,
Justin Lebarb44f6fe2016-01-14 21:41:21 +00003910 bool AtTopLevel, bool MultipleArchs, const char *LinkingOutput,
Samuel Antaod06239d2016-07-15 23:13:27 +00003911 std::map<std::pair<const Action *, std::string>, InputInfo> &CachedResults,
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003912 Action::OffloadKind TargetDeviceOffloadKind) const {
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00003913 llvm::PrettyStackTraceString CrashInfo("Building compilation jobs");
Daniel Dunbarc4acf9d2009-03-18 23:18:19 +00003914
Samuel Antaod06239d2016-07-15 23:13:27 +00003915 InputInfoList OffloadDependencesInputInfo;
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003916 bool BuildingForOffloadDevice = TargetDeviceOffloadKind != Action::OFK_None;
Samuel Antaod06239d2016-07-15 23:13:27 +00003917 if (const OffloadAction *OA = dyn_cast<OffloadAction>(A)) {
Alex Lorenz4003a982017-08-08 11:22:21 +00003918 // The 'Darwin' toolchain is initialized only when its arguments are
3919 // computed. Get the default arguments for OFK_None to ensure that
3920 // initialization is performed before processing the offload action.
3921 // FIXME: Remove when darwin's toolchain is initialized during construction.
3922 C.getArgsForToolChain(TC, BoundArch, Action::OFK_None);
3923
Samuel Antaod06239d2016-07-15 23:13:27 +00003924 // The offload action is expected to be used in four different situations.
3925 //
3926 // a) Set a toolchain/architecture/kind for a host action:
3927 // Host Action 1 -> OffloadAction -> Host Action 2
3928 //
3929 // b) Set a toolchain/architecture/kind for a device action;
3930 // Device Action 1 -> OffloadAction -> Device Action 2
3931 //
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00003932 // c) Specify a device dependence to a host action;
Samuel Antaod06239d2016-07-15 23:13:27 +00003933 // Device Action 1 _
3934 // \
3935 // Host Action 1 ---> OffloadAction -> Host Action 2
3936 //
3937 // d) Specify a host dependence to a device action.
3938 // Host Action 1 _
3939 // \
3940 // Device Action 1 ---> OffloadAction -> Device Action 2
3941 //
3942 // For a) and b), we just return the job generated for the dependence. For
3943 // c) and d) we override the current action with the host/device dependence
3944 // if the current toolchain is host/device and set the offload dependences
3945 // info with the jobs obtained from the device/host dependence(s).
3946
3947 // If there is a single device option, just generate the job for it.
3948 if (OA->hasSingleDeviceDependence()) {
3949 InputInfo DevA;
3950 OA->doOnEachDeviceDependence([&](Action *DepA, const ToolChain *DepTC,
3951 const char *DepBoundArch) {
3952 DevA =
3953 BuildJobsForAction(C, DepA, DepTC, DepBoundArch, AtTopLevel,
3954 /*MultipleArchs*/ !!DepBoundArch, LinkingOutput,
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003955 CachedResults, DepA->getOffloadingDeviceKind());
Samuel Antaod06239d2016-07-15 23:13:27 +00003956 });
3957 return DevA;
Artem Belevich0ff05cd2015-07-13 23:27:56 +00003958 }
Samuel Antaod06239d2016-07-15 23:13:27 +00003959
3960 // If 'Action 2' is host, we generate jobs for the device dependences and
3961 // override the current action with the host dependence. Otherwise, we
3962 // generate the host dependences and override the action with the device
3963 // dependence. The dependences can't therefore be a top-level action.
3964 OA->doOnEachDependence(
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003965 /*IsHostDependence=*/BuildingForOffloadDevice,
Samuel Antaod06239d2016-07-15 23:13:27 +00003966 [&](Action *DepA, const ToolChain *DepTC, const char *DepBoundArch) {
3967 OffloadDependencesInputInfo.push_back(BuildJobsForAction(
3968 C, DepA, DepTC, DepBoundArch, /*AtTopLevel=*/false,
3969 /*MultipleArchs*/ !!DepBoundArch, LinkingOutput, CachedResults,
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003970 DepA->getOffloadingDeviceKind()));
Samuel Antaod06239d2016-07-15 23:13:27 +00003971 });
3972
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003973 A = BuildingForOffloadDevice
Samuel Antaod06239d2016-07-15 23:13:27 +00003974 ? OA->getSingleDeviceDependence(/*DoNotConsiderHostActions=*/true)
3975 : OA->getHostDependence();
Artem Belevich0ff05cd2015-07-13 23:27:56 +00003976 }
3977
Daniel Dunbare75d8342009-03-16 06:56:51 +00003978 if (const InputAction *IA = dyn_cast<InputAction>(A)) {
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00003979 // FIXME: It would be nice to not claim this here; maybe the old scheme of
3980 // just using Args was better?
Daniel Dunbar5cdf3e02009-03-19 07:29:38 +00003981 const Arg &Input = IA->getInputArg();
3982 Input.claim();
Daniel Dunbar35cbfeb2010-06-09 22:31:08 +00003983 if (Input.getOption().matches(options::OPT_INPUT)) {
Richard Smithbd55daf2012-11-01 04:30:05 +00003984 const char *Name = Input.getValue();
Justin Lebard98cea82016-01-11 23:15:21 +00003985 return InputInfo(A, Name, /* BaseInput = */ Name);
Douglas Katzman678d0cb2015-06-16 18:01:24 +00003986 }
Justin Lebard98cea82016-01-11 23:15:21 +00003987 return InputInfo(A, &Input, /* BaseInput = */ "");
Daniel Dunbare75d8342009-03-16 06:56:51 +00003988 }
3989
3990 if (const BindArchAction *BAA = dyn_cast<BindArchAction>(A)) {
Chad Rosiera78a6eb2012-04-27 16:50:38 +00003991 const ToolChain *TC;
Mehdi Aminic50b1a22016-10-07 21:27:26 +00003992 StringRef ArchName = BAA->getArchName();
Daniel Dunbar1ef3f2a2009-09-08 23:37:19 +00003993
Mehdi Aminic50b1a22016-10-07 21:27:26 +00003994 if (!ArchName.empty())
Andrey Turetskiy6a8b91d2016-04-21 10:16:48 +00003995 TC = &getToolChain(C.getArgs(),
Petr Hosekdd38d932018-05-29 22:35:39 +00003996 computeTargetTriple(*this, TargetTriple,
Andrey Turetskiy6a8b91d2016-04-21 10:16:48 +00003997 C.getArgs(), ArchName));
Chad Rosiera78a6eb2012-04-27 16:50:38 +00003998 else
3999 TC = &C.getDefaultToolChain();
Daniel Dunbar1ef3f2a2009-09-08 23:37:19 +00004000
Nico Weber5a459f82016-02-23 19:30:43 +00004001 return BuildJobsForAction(C, *BAA->input_begin(), TC, ArchName, AtTopLevel,
Samuel Antaod06239d2016-07-15 23:13:27 +00004002 MultipleArchs, LinkingOutput, CachedResults,
Samuel Antao3b7e38b2016-10-27 18:14:55 +00004003 TargetDeviceOffloadKind);
Daniel Dunbare75d8342009-03-16 06:56:51 +00004004 }
4005
Artem Belevich0ff05cd2015-07-13 23:27:56 +00004006
Richard Smithcd35eff2018-09-15 01:21:16 +00004007 ActionList Inputs = A->getInputs();
Daniel Dunbarc4343942010-02-03 03:07:56 +00004008
4009 const JobAction *JA = cast<JobAction>(A);
Samuel Antaod06239d2016-07-15 23:13:27 +00004010 ActionList CollapsedOffloadActions;
4011
Mehdi Amini6683e222017-01-24 18:12:25 +00004012 ToolSelector TS(JA, *TC, C, isSaveTempsEnabled(),
4013 embedBitcodeInObject() && !isUsingLTO());
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00004014 const Tool *T = TS.getTool(Inputs, CollapsedOffloadActions);
4015
Rafael Espindola79764462013-03-24 15:06:53 +00004016 if (!T)
Justin Lebar9eaa4892016-01-11 23:09:32 +00004017 return InputInfo();
Daniel Dunbare75d8342009-03-16 06:56:51 +00004018
Samuel Antaod06239d2016-07-15 23:13:27 +00004019 // If we've collapsed action list that contained OffloadAction we
4020 // need to build jobs for host/device-side inputs it may have held.
4021 for (const auto *OA : CollapsedOffloadActions)
4022 cast<OffloadAction>(OA)->doOnEachDependence(
Samuel Antao3b7e38b2016-10-27 18:14:55 +00004023 /*IsHostDependence=*/BuildingForOffloadDevice,
Samuel Antaod06239d2016-07-15 23:13:27 +00004024 [&](Action *DepA, const ToolChain *DepTC, const char *DepBoundArch) {
4025 OffloadDependencesInputInfo.push_back(BuildJobsForAction(
Artem Belevichbee2f412016-08-22 18:50:34 +00004026 C, DepA, DepTC, DepBoundArch, /* AtTopLevel */ false,
Samuel Antaod06239d2016-07-15 23:13:27 +00004027 /*MultipleArchs=*/!!DepBoundArch, LinkingOutput, CachedResults,
Samuel Antao3b7e38b2016-10-27 18:14:55 +00004028 DepA->getOffloadingDeviceKind()));
Samuel Antaod06239d2016-07-15 23:13:27 +00004029 });
Artem Belevichf8144ab2015-08-27 18:10:41 +00004030
Daniel Dunbare75d8342009-03-16 06:56:51 +00004031 // Only use pipes when there is exactly one input.
Daniel Dunbar1a093d22009-03-18 06:00:36 +00004032 InputInfoList InputInfos;
Richard Smithcd35eff2018-09-15 01:21:16 +00004033 for (const Action *Input : Inputs) {
Eric Christopher14668dd2013-02-18 00:38:25 +00004034 // Treat dsymutil and verify sub-jobs as being at the top-level too, they
4035 // shouldn't get temporary output names.
Daniel Dunbar6beaf512010-06-04 18:28:41 +00004036 // FIXME: Clean this up.
Justin Lebar9eaa4892016-01-11 23:09:32 +00004037 bool SubJobAtTopLevel =
4038 AtTopLevel && (isa<DsymutilJobAction>(A) || isa<VerifyJobAction>(A));
Samuel Antaod06239d2016-07-15 23:13:27 +00004039 InputInfos.push_back(BuildJobsForAction(
4040 C, Input, TC, BoundArch, SubJobAtTopLevel, MultipleArchs, LinkingOutput,
Samuel Antao3b7e38b2016-10-27 18:14:55 +00004041 CachedResults, A->getOffloadingDeviceKind()));
Daniel Dunbare75d8342009-03-16 06:56:51 +00004042 }
4043
Daniel Dunbare75d8342009-03-16 06:56:51 +00004044 // Always use the first input as the base input.
4045 const char *BaseInput = InputInfos[0].getBaseInput();
Daniel Dunbar7a178a42009-03-17 17:53:55 +00004046
Daniel Dunbar6beaf512010-06-04 18:28:41 +00004047 // ... except dsymutil actions, which use their actual input as the base
4048 // input.
4049 if (JA->getType() == types::TY_dSYM)
4050 BaseInput = InputInfos[0].getFilename();
4051
Richard Smithcd35eff2018-09-15 01:21:16 +00004052 // ... and in header module compilations, which use the module name.
4053 if (auto *ModuleJA = dyn_cast<HeaderModulePrecompileJobAction>(JA))
4054 BaseInput = ModuleJA->getModuleName();
4055
Samuel Antaod06239d2016-07-15 23:13:27 +00004056 // Append outputs of offload device jobs to the input list
4057 if (!OffloadDependencesInputInfo.empty())
4058 InputInfos.append(OffloadDependencesInputInfo.begin(),
4059 OffloadDependencesInputInfo.end());
Artem Belevich0ff05cd2015-07-13 23:27:56 +00004060
Vedant Kumar18286cf2016-07-27 23:02:20 +00004061 // Set the effective triple of the toolchain for the duration of this job.
4062 llvm::Triple EffectiveTriple;
4063 const ToolChain &ToolTC = T->getToolChain();
Samuel Antao31fef982016-10-27 17:39:44 +00004064 const ArgList &Args =
4065 C.getArgsForToolChain(TC, BoundArch, A->getOffloadingDeviceKind());
Vedant Kumar18286cf2016-07-27 23:02:20 +00004066 if (InputInfos.size() != 1) {
4067 EffectiveTriple = llvm::Triple(ToolTC.ComputeEffectiveClangTriple(Args));
4068 } else {
4069 // Pass along the input type if it can be unambiguously determined.
4070 EffectiveTriple = llvm::Triple(
4071 ToolTC.ComputeEffectiveClangTriple(Args, InputInfos[0].getType()));
4072 }
4073 RegisterEffectiveTriple TripleRAII(ToolTC, EffectiveTriple);
4074
Daniel Dunbard00272f2010-08-02 02:38:15 +00004075 // Determine the place to write output to, if any.
Justin Lebar9eaa4892016-01-11 23:09:32 +00004076 InputInfo Result;
Samuel Antao3b7e38b2016-10-27 18:14:55 +00004077 InputInfoList UnbundlingResults;
4078 if (auto *UA = dyn_cast<OffloadUnbundlingJobAction>(JA)) {
4079 // If we have an unbundling job, we need to create results for all the
4080 // outputs. We also update the results cache so that other actions using
4081 // this unbundling action can get the right results.
4082 for (auto &UI : UA->getDependentActionsInfo()) {
4083 assert(UI.DependentOffloadKind != Action::OFK_None &&
4084 "Unbundling with no offloading??");
4085
4086 // Unbundling actions are never at the top level. When we generate the
4087 // offloading prefix, we also do that for the host file because the
4088 // unbundling action does not change the type of the output which can
4089 // cause a overwrite.
4090 std::string OffloadingPrefix = Action::GetOffloadingFileNamePrefix(
4091 UI.DependentOffloadKind,
4092 UI.DependentToolChain->getTriple().normalize(),
4093 /*CreatePrefixForHost=*/true);
4094 auto CurI = InputInfo(
Yaxun Liu609f7522018-05-11 19:02:18 +00004095 UA,
4096 GetNamedOutputPath(C, *UA, BaseInput, UI.DependentBoundArch,
4097 /*AtTopLevel=*/false,
4098 MultipleArchs ||
4099 UI.DependentOffloadKind == Action::OFK_HIP,
4100 OffloadingPrefix),
Samuel Antao3b7e38b2016-10-27 18:14:55 +00004101 BaseInput);
4102 // Save the unbundling result.
4103 UnbundlingResults.push_back(CurI);
4104
4105 // Get the unique string identifier for this dependence and cache the
4106 // result.
Yaxun Liu470b8332018-06-06 19:44:10 +00004107 StringRef Arch;
4108 if (TargetDeviceOffloadKind == Action::OFK_HIP) {
4109 if (UI.DependentOffloadKind == Action::OFK_Host)
Yaxun Liuf37b50a2018-07-24 01:03:44 +00004110 Arch = StringRef();
Yaxun Liu470b8332018-06-06 19:44:10 +00004111 else
4112 Arch = UI.DependentBoundArch;
4113 } else
4114 Arch = BoundArch;
4115
4116 CachedResults[{A, GetTriplePlusArchString(UI.DependentToolChain, Arch,
4117 UI.DependentOffloadKind)}] =
4118 CurI;
Samuel Antao3b7e38b2016-10-27 18:14:55 +00004119 }
4120
4121 // Now that we have all the results generated, select the one that should be
4122 // returned for the current depending action.
4123 std::pair<const Action *, std::string> ActionTC = {
4124 A, GetTriplePlusArchString(TC, BoundArch, TargetDeviceOffloadKind)};
4125 assert(CachedResults.find(ActionTC) != CachedResults.end() &&
4126 "Result does not exist??");
4127 Result = CachedResults[ActionTC];
4128 } else if (JA->getType() == types::TY_Nothing)
Justin Lebard98cea82016-01-11 23:15:21 +00004129 Result = InputInfo(A, BaseInput);
Samuel Antao3b7e38b2016-10-27 18:14:55 +00004130 else {
4131 // We only have to generate a prefix for the host if this is not a top-level
4132 // action.
4133 std::string OffloadingPrefix = Action::GetOffloadingFileNamePrefix(
4134 A->getOffloadingDeviceKind(), TC->getTriple().normalize(),
4135 /*CreatePrefixForHost=*/!!A->getOffloadingHostActiveKinds() &&
4136 !AtTopLevel);
Justin Lebard98cea82016-01-11 23:15:21 +00004137 Result = InputInfo(A, GetNamedOutputPath(C, *JA, BaseInput, BoundArch,
Samuel Antaod06239d2016-07-15 23:13:27 +00004138 AtTopLevel, MultipleArchs,
Samuel Antao3b7e38b2016-10-27 18:14:55 +00004139 OffloadingPrefix),
Justin Lebard98cea82016-01-11 23:15:21 +00004140 BaseInput);
Samuel Antao3b7e38b2016-10-27 18:14:55 +00004141 }
Daniel Dunbar7a178a42009-03-17 17:53:55 +00004142
Chad Rosierbe10f982011-08-02 17:58:04 +00004143 if (CCCPrintBindings && !CCGenDiagnostics) {
Rafael Espindola79764462013-03-24 15:06:53 +00004144 llvm::errs() << "# \"" << T->getToolChain().getTripleString() << '"'
4145 << " - \"" << T->getName() << "\", inputs: [";
Daniel Dunbarb39cc522009-03-17 22:47:06 +00004146 for (unsigned i = 0, e = InputInfos.size(); i != e; ++i) {
4147 llvm::errs() << InputInfos[i].getAsString();
4148 if (i + 1 != e)
4149 llvm::errs() << ", ";
4150 }
Samuel Antao3b7e38b2016-10-27 18:14:55 +00004151 if (UnbundlingResults.empty())
4152 llvm::errs() << "], output: " << Result.getAsString() << "\n";
4153 else {
4154 llvm::errs() << "], outputs: [";
4155 for (unsigned i = 0, e = UnbundlingResults.size(); i != e; ++i) {
4156 llvm::errs() << UnbundlingResults[i].getAsString();
4157 if (i + 1 != e)
4158 llvm::errs() << ", ";
4159 }
4160 llvm::errs() << "] \n";
4161 }
Daniel Dunbarb39cc522009-03-17 22:47:06 +00004162 } else {
Samuel Antao3b7e38b2016-10-27 18:14:55 +00004163 if (UnbundlingResults.empty())
4164 T->ConstructJob(
4165 C, *JA, Result, InputInfos,
4166 C.getArgsForToolChain(TC, BoundArch, JA->getOffloadingDeviceKind()),
4167 LinkingOutput);
4168 else
Samuel Antao7108bf32016-11-03 15:41:50 +00004169 T->ConstructJobMultipleOutputs(
Samuel Antao3b7e38b2016-10-27 18:14:55 +00004170 C, *JA, UnbundlingResults, InputInfos,
4171 C.getArgsForToolChain(TC, BoundArch, JA->getOffloadingDeviceKind()),
4172 LinkingOutput);
Daniel Dunbarb39cc522009-03-17 22:47:06 +00004173 }
Justin Lebar9eaa4892016-01-11 23:09:32 +00004174 return Result;
Daniel Dunbare75d8342009-03-16 06:56:51 +00004175}
4176
Hans Wennborga7707222015-01-09 17:38:53 +00004177const char *Driver::getDefaultImageName() const {
Petr Hosekdd38d932018-05-29 22:35:39 +00004178 llvm::Triple Target(llvm::Triple::normalize(TargetTriple));
Hans Wennborga7707222015-01-09 17:38:53 +00004179 return Target.isOSWindows() ? "a.exe" : "a.out";
4180}
4181
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004182/// Create output filename based on ArgValue, which could either be a
Hans Wennborg2c21f742013-10-17 16:16:23 +00004183/// full filename, filename without extension, or a directory. If ArgValue
4184/// does not provide a filename, then use BaseName, and use the extension
4185/// suitable for FileType.
Hans Wennborg207fcf02013-08-12 21:56:42 +00004186static const char *MakeCLOutputFilename(const ArgList &Args, StringRef ArgValue,
Douglas Katzmana67e50c2015-06-26 15:47:46 +00004187 StringRef BaseName,
4188 types::ID FileType) {
Hans Wennborg207fcf02013-08-12 21:56:42 +00004189 SmallString<128> Filename = ArgValue;
Justin Bogner5aaf2e72014-06-26 20:59:36 +00004190
Hans Wennborgf1a74252013-09-10 20:18:04 +00004191 if (ArgValue.empty()) {
4192 // If the argument is empty, output to BaseName in the current dir.
4193 Filename = BaseName;
4194 } else if (llvm::sys::path::is_separator(Filename.back())) {
Hans Wennborg207fcf02013-08-12 21:56:42 +00004195 // If the argument is a directory, output to BaseName in that dir.
4196 llvm::sys::path::append(Filename, BaseName);
4197 }
4198
4199 if (!llvm::sys::path::has_extension(ArgValue)) {
4200 // If the argument didn't provide an extension, then set it.
4201 const char *Extension = types::getTypeTempSuffix(FileType, true);
Hans Wennborgf1a74252013-09-10 20:18:04 +00004202
4203 if (FileType == types::TY_Image &&
4204 Args.hasArg(options::OPT__SLASH_LD, options::OPT__SLASH_LDd)) {
4205 // The output file is a dll.
4206 Extension = "dll";
4207 }
4208
Hans Wennborg207fcf02013-08-12 21:56:42 +00004209 llvm::sys::path::replace_extension(Filename, Extension);
4210 }
4211
4212 return Args.MakeArgString(Filename.c_str());
4213}
4214
Douglas Katzmana67e50c2015-06-26 15:47:46 +00004215const char *Driver::GetNamedOutputPath(Compilation &C, const JobAction &JA,
Daniel Dunbar7a178a42009-03-17 17:53:55 +00004216 const char *BaseInput,
Mehdi Aminic50b1a22016-10-07 21:27:26 +00004217 StringRef BoundArch, bool AtTopLevel,
Samuel Antaod06239d2016-07-15 23:13:27 +00004218 bool MultipleArchs,
Samuel Antao3b7e38b2016-10-27 18:14:55 +00004219 StringRef OffloadingPrefix) const {
Daniel Dunbar2608c542009-03-18 01:38:48 +00004220 llvm::PrettyStackTraceString CrashInfo("Computing output path");
Daniel Dunbar7a178a42009-03-17 17:53:55 +00004221 // Output to a user requested destination?
Douglas Katzmana67e50c2015-06-26 15:47:46 +00004222 if (AtTopLevel && !isa<DsymutilJobAction>(JA) && !isa<VerifyJobAction>(JA)) {
Daniel Dunbar7a178a42009-03-17 17:53:55 +00004223 if (Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o))
Chad Rosier633dcdc2013-01-24 19:14:47 +00004224 return C.addResultFile(FinalOutput->getValue(), &JA);
Daniel Dunbar7a178a42009-03-17 17:53:55 +00004225 }
4226
Hans Wennborge0053472013-12-20 18:40:46 +00004227 // For /P, preprocess to file named after BaseInput.
4228 if (C.getArgs().hasArg(options::OPT__SLASH_P)) {
4229 assert(AtTopLevel && isa<PreprocessJobAction>(JA));
4230 StringRef BaseName = llvm::sys::path::filename(BaseInput);
Hans Wennborg04c764f2014-06-17 00:19:12 +00004231 StringRef NameArg;
Greg Bedwell065f70a2015-06-09 10:24:06 +00004232 if (Arg *A = C.getArgs().getLastArg(options::OPT__SLASH_Fi))
Hans Wennborg04c764f2014-06-17 00:19:12 +00004233 NameArg = A->getValue();
Douglas Katzmana67e50c2015-06-26 15:47:46 +00004234 return C.addResultFile(
4235 MakeCLOutputFilename(C.getArgs(), NameArg, BaseName, types::TY_PP_C),
4236 &JA);
Hans Wennborge0053472013-12-20 18:40:46 +00004237 }
4238
Nick Lewycky6e1ce292010-09-24 00:46:53 +00004239 // Default to writing to stdout?
David Blaikiebc023c92018-06-14 23:09:06 +00004240 if (AtTopLevel && !CCGenDiagnostics && isa<PreprocessJobAction>(JA))
Nick Lewycky6e1ce292010-09-24 00:46:53 +00004241 return "-";
4242
Hans Wennborg2c21f742013-10-17 16:16:23 +00004243 // Is this the assembly listing for /FA?
4244 if (JA.getType() == types::TY_PP_Asm &&
4245 (C.getArgs().hasArg(options::OPT__SLASH_FA) ||
4246 C.getArgs().hasArg(options::OPT__SLASH_Fa))) {
4247 // Use /Fa and the input filename to determine the asm file name.
4248 StringRef BaseName = llvm::sys::path::filename(BaseInput);
4249 StringRef FaValue = C.getArgs().getLastArgValue(options::OPT__SLASH_Fa);
Douglas Katzmana67e50c2015-06-26 15:47:46 +00004250 return C.addResultFile(
4251 MakeCLOutputFilename(C.getArgs(), FaValue, BaseName, JA.getType()),
4252 &JA);
Hans Wennborg2c21f742013-10-17 16:16:23 +00004253 }
4254
Daniel Dunbar7a178a42009-03-17 17:53:55 +00004255 // Output to a temporary file?
Reid Kleckner68eb60b2015-02-02 22:41:48 +00004256 if ((!AtTopLevel && !isSaveTempsEnabled() &&
Douglas Katzmana67e50c2015-06-26 15:47:46 +00004257 !C.getArgs().hasArg(options::OPT__SLASH_Fo)) ||
Chad Rosierbe10f982011-08-02 17:58:04 +00004258 CCGenDiagnostics) {
Chad Rosier97c37372011-08-26 22:27:02 +00004259 StringRef Name = llvm::sys::path::filename(BaseInput);
4260 std::pair<StringRef, StringRef> Split = Name.split('.');
Bob Haarman7e4d3ff2018-07-09 21:07:20 +00004261 SmallString<128> TmpName;
4262 const char *Suffix = types::getTypeTempSuffix(JA.getType(), IsCLMode());
4263 Arg *A = C.getArgs().getLastArg(options::OPT_fcrash_diagnostics_dir);
4264 if (CCGenDiagnostics && A) {
4265 SmallString<128> CrashDirectory(A->getValue());
4266 llvm::sys::path::append(CrashDirectory, Split.first);
4267 const char *Middle = Suffix ? "-%%%%%%." : "-%%%%%%";
Simon Atanasyan27c0f202019-04-02 18:03:15 +00004268 std::error_code EC = llvm::sys::fs::createUniqueFile(
4269 CrashDirectory + Middle + Suffix, TmpName);
Bob Haarman7e4d3ff2018-07-09 21:07:20 +00004270 if (EC) {
4271 Diag(clang::diag::err_unable_to_make_temp) << EC.message();
4272 return "";
4273 }
4274 } else {
4275 TmpName = GetTemporaryPath(Split.first, Suffix);
4276 }
Malcolm Parsonsf76f6502016-11-02 10:39:27 +00004277 return C.addTempFile(C.getArgs().MakeArgString(TmpName));
Daniel Dunbar7a178a42009-03-17 17:53:55 +00004278 }
4279
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00004280 SmallString<128> BasePath(BaseInput);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004281 StringRef BaseName;
Daniel Dunbar67fea712011-03-25 18:16:51 +00004282
4283 // Dsymutil actions should use the full path.
Eric Christopher551ef452011-08-23 17:56:55 +00004284 if (isa<DsymutilJobAction>(JA) || isa<VerifyJobAction>(JA))
Daniel Dunbar67fea712011-03-25 18:16:51 +00004285 BaseName = BasePath;
4286 else
4287 BaseName = llvm::sys::path::filename(BasePath);
Daniel Dunbar7a178a42009-03-17 17:53:55 +00004288
4289 // Determine what the derived output name should be.
4290 const char *NamedOutput;
Hans Wennborg2b89a262013-08-06 22:11:28 +00004291
Hans Wennborg625fba82016-10-04 21:01:04 +00004292 if ((JA.getType() == types::TY_Object || JA.getType() == types::TY_LTO_BC) &&
Ehsan Akhgari81f36b72014-09-11 18:16:21 +00004293 C.getArgs().hasArg(options::OPT__SLASH_Fo, options::OPT__SLASH_o)) {
4294 // The /Fo or /o flag decides the object filename.
Douglas Katzmana67e50c2015-06-26 15:47:46 +00004295 StringRef Val =
4296 C.getArgs()
4297 .getLastArg(options::OPT__SLASH_Fo, options::OPT__SLASH_o)
4298 ->getValue();
4299 NamedOutput =
4300 MakeCLOutputFilename(C.getArgs(), Val, BaseName, types::TY_Object);
Hans Wennborg207fcf02013-08-12 21:56:42 +00004301 } else if (JA.getType() == types::TY_Image &&
Douglas Katzmana67e50c2015-06-26 15:47:46 +00004302 C.getArgs().hasArg(options::OPT__SLASH_Fe,
4303 options::OPT__SLASH_o)) {
Ehsan Akhgari81f36b72014-09-11 18:16:21 +00004304 // The /Fe or /o flag names the linked file.
Douglas Katzmana67e50c2015-06-26 15:47:46 +00004305 StringRef Val =
4306 C.getArgs()
4307 .getLastArg(options::OPT__SLASH_Fe, options::OPT__SLASH_o)
4308 ->getValue();
4309 NamedOutput =
4310 MakeCLOutputFilename(C.getArgs(), Val, BaseName, types::TY_Image);
Hans Wennborgf1a74252013-09-10 20:18:04 +00004311 } else if (JA.getType() == types::TY_Image) {
Hans Wennborg207fcf02013-08-12 21:56:42 +00004312 if (IsCLMode()) {
4313 // clang-cl uses BaseName for the executable name.
Douglas Katzmana67e50c2015-06-26 15:47:46 +00004314 NamedOutput =
4315 MakeCLOutputFilename(C.getArgs(), "", BaseName, types::TY_Image);
Samuel Antao59efaed2016-10-27 17:31:22 +00004316 } else {
Hans Wennborga7707222015-01-09 17:38:53 +00004317 SmallString<128> Output(getDefaultImageName());
Samuel Antao3b7e38b2016-10-27 18:14:55 +00004318 Output += OffloadingPrefix;
Samuel Antao59efaed2016-10-27 17:31:22 +00004319 if (MultipleArchs && !BoundArch.empty()) {
4320 Output += "-";
4321 Output.append(BoundArch);
4322 }
Chad Rosier35767232013-04-30 22:01:21 +00004323 NamedOutput = C.getArgs().MakeArgString(Output.c_str());
Nico Weber2ca4be92016-03-01 23:16:44 +00004324 }
4325 } else if (JA.getType() == types::TY_PCH && IsCLMode()) {
Malcolm Parsonsf76f6502016-11-02 10:39:27 +00004326 NamedOutput = C.getArgs().MakeArgString(GetClPchPath(C, BaseName));
Daniel Dunbar7a178a42009-03-17 17:53:55 +00004327 } else {
Hans Wennborg0a096a02013-09-05 17:05:56 +00004328 const char *Suffix = types::getTypeTempSuffix(JA.getType(), IsCLMode());
Daniel Dunbar7a178a42009-03-17 17:53:55 +00004329 assert(Suffix && "All types used for output should have a suffix.");
4330
4331 std::string::size_type End = std::string::npos;
4332 if (!types::appendSuffixForType(JA.getType()))
4333 End = BaseName.rfind('.');
Chad Rosier35767232013-04-30 22:01:21 +00004334 SmallString<128> Suffixed(BaseName.substr(0, End));
Samuel Antao3b7e38b2016-10-27 18:14:55 +00004335 Suffixed += OffloadingPrefix;
Mehdi Aminic50b1a22016-10-07 21:27:26 +00004336 if (MultipleArchs && !BoundArch.empty()) {
Chad Rosier35767232013-04-30 22:01:21 +00004337 Suffixed += "-";
4338 Suffixed.append(BoundArch);
4339 }
Bob Wilson23a55f12014-12-21 07:00:00 +00004340 // When using both -save-temps and -emit-llvm, use a ".tmp.bc" suffix for
4341 // the unoptimized bitcode so that it does not get overwritten by the ".bc"
4342 // optimized bitcode output.
4343 if (!AtTopLevel && C.getArgs().hasArg(options::OPT_emit_llvm) &&
4344 JA.getType() == types::TY_LLVM_BC)
4345 Suffixed += ".tmp";
Daniel Dunbar7a178a42009-03-17 17:53:55 +00004346 Suffixed += '.';
4347 Suffixed += Suffix;
4348 NamedOutput = C.getArgs().MakeArgString(Suffixed.c_str());
4349 }
4350
Reid Kleckner68eb60b2015-02-02 22:41:48 +00004351 // Prepend object file path if -save-temps=obj
4352 if (!AtTopLevel && isSaveTempsObj() && C.getArgs().hasArg(options::OPT_o) &&
4353 JA.getType() != types::TY_PCH) {
4354 Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o);
4355 SmallString<128> TempPath(FinalOutput->getValue());
4356 llvm::sys::path::remove_filename(TempPath);
4357 StringRef OutputFileName = llvm::sys::path::filename(NamedOutput);
4358 llvm::sys::path::append(TempPath, OutputFileName);
4359 NamedOutput = C.getArgs().MakeArgString(TempPath.c_str());
4360 }
4361
Chad Rosier62135492012-07-09 17:31:28 +00004362 // If we're saving temps and the temp file conflicts with the input file,
Chad Rosier5b58af02012-04-20 20:05:08 +00004363 // then avoid overwriting input file.
Reid Kleckner68eb60b2015-02-02 22:41:48 +00004364 if (!AtTopLevel && isSaveTempsEnabled() && NamedOutput == BaseName) {
Chad Rosier5b58af02012-04-20 20:05:08 +00004365 bool SameFile = false;
4366 SmallString<256> Result;
4367 llvm::sys::fs::current_path(Result);
4368 llvm::sys::path::append(Result, BaseName);
4369 llvm::sys::fs::equivalent(BaseInput, Result.c_str(), SameFile);
4370 // Must share the same path to conflict.
4371 if (SameFile) {
4372 StringRef Name = llvm::sys::path::filename(BaseInput);
4373 std::pair<StringRef, StringRef> Split = Name.split('.');
Douglas Katzmana67e50c2015-06-26 15:47:46 +00004374 std::string TmpName = GetTemporaryPath(
4375 Split.first, types::getTypeTempSuffix(JA.getType(), IsCLMode()));
Malcolm Parsonsf76f6502016-11-02 10:39:27 +00004376 return C.addTempFile(C.getArgs().MakeArgString(TmpName));
Chad Rosier5b58af02012-04-20 20:05:08 +00004377 }
Chad Rosierf8412cd2011-07-15 21:54:29 +00004378 }
4379
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00004380 // As an annoying special case, PCH generation doesn't strip the pathname.
Nico Weber8ab92192016-03-02 23:29:29 +00004381 if (JA.getType() == types::TY_PCH && !IsCLMode()) {
Michael J. Spencere1696752010-12-18 00:19:12 +00004382 llvm::sys::path::remove_filename(BasePath);
4383 if (BasePath.empty())
Daniel Dunbare6c83192009-03-18 09:58:30 +00004384 BasePath = NamedOutput;
4385 else
Michael J. Spencere1696752010-12-18 00:19:12 +00004386 llvm::sys::path::append(BasePath, NamedOutput);
Chad Rosier633dcdc2013-01-24 19:14:47 +00004387 return C.addResultFile(C.getArgs().MakeArgString(BasePath.c_str()), &JA);
Daniel Dunbar7a178a42009-03-17 17:53:55 +00004388 } else {
Chad Rosier633dcdc2013-01-24 19:14:47 +00004389 return C.addResultFile(NamedOutput, &JA);
Daniel Dunbar7a178a42009-03-17 17:53:55 +00004390 }
4391}
4392
Mehdi Amini12011172016-10-06 05:11:48 +00004393std::string Driver::GetFilePath(StringRef Name, const ToolChain &TC) const {
Raphael Isemannb23ccec2018-12-10 12:37:46 +00004394 // Search for Name in a list of paths.
Petr Hosek8f2499f2018-09-12 03:26:10 +00004395 auto SearchPaths = [&](const llvm::SmallVectorImpl<std::string> &P)
4396 -> llvm::Optional<std::string> {
4397 // Respect a limited subset of the '-Bprefix' functionality in GCC by
4398 // attempting to use this prefix when looking for file paths.
4399 for (const auto &Dir : P) {
4400 if (Dir.empty())
4401 continue;
4402 SmallString<128> P(Dir[0] == '=' ? SysRoot + Dir.substr(1) : Dir);
4403 llvm::sys::path::append(P, Name);
4404 if (llvm::sys::fs::exists(Twine(P)))
Simon Pilgrim4588fc82018-09-13 10:10:18 +00004405 return P.str().str();
Petr Hosek8f2499f2018-09-12 03:26:10 +00004406 }
4407 return None;
4408 };
4409
4410 if (auto P = SearchPaths(PrefixDirs))
4411 return *P;
Chandler Carruth84559242010-03-22 01:52:07 +00004412
Petr Hosek916a4672017-08-10 04:16:38 +00004413 SmallString<128> R(ResourceDir);
4414 llvm::sys::path::append(R, Name);
4415 if (llvm::sys::fs::exists(Twine(R)))
4416 return R.str();
4417
4418 SmallString<128> P(TC.getCompilerRTPath());
Rafael Espindola609a6642013-06-24 18:33:43 +00004419 llvm::sys::path::append(P, Name);
4420 if (llvm::sys::fs::exists(Twine(P)))
Peter Collingbournefa9771f2011-09-06 02:08:31 +00004421 return P.str();
4422
Petr Hosek8f2499f2018-09-12 03:26:10 +00004423 if (auto P = SearchPaths(TC.getLibraryPaths()))
4424 return *P;
4425
4426 if (auto P = SearchPaths(TC.getFilePaths()))
4427 return *P;
Daniel Dunbar68b01a02009-03-18 20:26:19 +00004428
Daniel Dunbar1ce81532009-09-09 22:33:00 +00004429 return Name;
Daniel Dunbar5e0f6af2009-03-13 00:51:18 +00004430}
4431
Douglas Katzmana67e50c2015-06-26 15:47:46 +00004432void Driver::generatePrefixedToolNames(
Mehdi Amini12011172016-10-06 05:11:48 +00004433 StringRef Tool, const ToolChain &TC,
Douglas Katzmana67e50c2015-06-26 15:47:46 +00004434 SmallVectorImpl<std::string> &Names) const {
Petr Hosekdd38d932018-05-29 22:35:39 +00004435 // FIXME: Needs a better variable than TargetTriple
4436 Names.emplace_back((TargetTriple + "-" + Tool).str());
Benjamin Kramer3204b152015-05-29 19:42:19 +00004437 Names.emplace_back(Tool);
Vasileios Kalintirisc744e122015-11-12 15:26:54 +00004438
4439 // Allow the discovery of tools prefixed with LLVM's default target triple.
Petr Hosekdd38d932018-05-29 22:35:39 +00004440 std::string DefaultTargetTriple = llvm::sys::getDefaultTargetTriple();
4441 if (DefaultTargetTriple != TargetTriple)
4442 Names.emplace_back((DefaultTargetTriple + "-" + Tool).str());
Saleem Abdulrasoolf0ba6ce2014-10-25 23:33:21 +00004443}
4444
Benjamin Kramer7111b912014-11-04 20:26:01 +00004445static bool ScanDirForExecutable(SmallString<128> &Dir,
4446 ArrayRef<std::string> Names) {
Saleem Abdulrasoolf0ba6ce2014-10-25 23:33:21 +00004447 for (const auto &Name : Names) {
4448 llvm::sys::path::append(Dir, Name);
4449 if (llvm::sys::fs::can_execute(Twine(Dir)))
4450 return true;
4451 llvm::sys::path::remove_filename(Dir);
4452 }
4453 return false;
4454}
4455
Mehdi Amini12011172016-10-06 05:11:48 +00004456std::string Driver::GetProgramPath(StringRef Name, const ToolChain &TC) const {
Saleem Abdulrasoolf0ba6ce2014-10-25 23:33:21 +00004457 SmallVector<std::string, 2> TargetSpecificExecutables;
4458 generatePrefixedToolNames(Name, TC, TargetSpecificExecutables);
4459
Chandler Carruth84559242010-03-22 01:52:07 +00004460 // Respect a limited subset of the '-Bprefix' functionality in GCC by
Logan Chiencd679fd2012-10-04 08:08:56 +00004461 // attempting to use this prefix when looking for program paths.
Saleem Abdulrasool23d99b12014-09-16 03:48:32 +00004462 for (const auto &PrefixDir : PrefixDirs) {
4463 if (llvm::sys::fs::is_directory(PrefixDir)) {
4464 SmallString<128> P(PrefixDir);
Saleem Abdulrasoolf0ba6ce2014-10-25 23:33:21 +00004465 if (ScanDirForExecutable(P, TargetSpecificExecutables))
Rafael Espindola8be5c052013-06-19 13:24:29 +00004466 return P.str();
Simon Atanasyana47ba292012-10-31 14:39:28 +00004467 } else {
Mehdi Amini12011172016-10-06 05:11:48 +00004468 SmallString<128> P((PrefixDir + Name).str());
Rafael Espindola609a6642013-06-24 18:33:43 +00004469 if (llvm::sys::fs::can_execute(Twine(P)))
Rafael Espindola8be5c052013-06-19 13:24:29 +00004470 return P.str();
Simon Atanasyan86bdab72012-10-31 12:01:53 +00004471 }
Chandler Carruth84559242010-03-22 01:52:07 +00004472 }
4473
Daniel Dunbar68b01a02009-03-18 20:26:19 +00004474 const ToolChain::path_list &List = TC.getProgramPaths();
Saleem Abdulrasool23d99b12014-09-16 03:48:32 +00004475 for (const auto &Path : List) {
4476 SmallString<128> P(Path);
Saleem Abdulrasoolf0ba6ce2014-10-25 23:33:21 +00004477 if (ScanDirForExecutable(P, TargetSpecificExecutables))
Rafael Espindola8be5c052013-06-19 13:24:29 +00004478 return P.str();
Daniel Dunbar68b01a02009-03-18 20:26:19 +00004479 }
4480
Daniel Dunbar76ce7412009-03-23 16:15:50 +00004481 // If all else failed, search the path.
Michael J. Spencerb011d482014-11-07 21:30:32 +00004482 for (const auto &TargetSpecificExecutable : TargetSpecificExecutables)
4483 if (llvm::ErrorOr<std::string> P =
4484 llvm::sys::findProgramByName(TargetSpecificExecutable))
Michael J. Spencer04162ea2014-11-04 01:30:55 +00004485 return *P;
Daniel Dunbar6f668772009-03-18 21:34:08 +00004486
Daniel Dunbar1ce81532009-09-09 22:33:00 +00004487 return Name;
Daniel Dunbar5e0f6af2009-03-13 00:51:18 +00004488}
4489
Mehdi Amini12011172016-10-06 05:11:48 +00004490std::string Driver::GetTemporaryPath(StringRef Prefix, StringRef Suffix) const {
Rafael Espindola37d229d2013-06-25 04:26:55 +00004491 SmallString<128> Path;
Rafael Espindolac0809172014-06-12 14:02:15 +00004492 std::error_code EC = llvm::sys::fs::createTemporaryFile(Prefix, Suffix, Path);
Rafael Espindola37d229d2013-06-25 04:26:55 +00004493 if (EC) {
4494 Diag(clang::diag::err_unable_to_make_temp) << EC.message();
Daniel Dunbare627c1c2009-03-18 19:34:39 +00004495 return "";
4496 }
4497
Rafael Espindola37d229d2013-06-25 04:26:55 +00004498 return Path.str();
Daniel Dunbare627c1c2009-03-18 19:34:39 +00004499}
4500
Steven Wuc3399db62019-01-11 21:16:04 +00004501std::string Driver::GetTemporaryDirectory(StringRef Prefix) const {
4502 SmallString<128> Path;
4503 std::error_code EC = llvm::sys::fs::createUniqueDirectory(Prefix, Path);
4504 if (EC) {
4505 Diag(clang::diag::err_unable_to_make_temp) << EC.message();
4506 return "";
4507 }
4508
4509 return Path.str();
4510}
4511
Nico Weber2ca4be92016-03-01 23:16:44 +00004512std::string Driver::GetClPchPath(Compilation &C, StringRef BaseName) const {
4513 SmallString<128> Output;
4514 if (Arg *FpArg = C.getArgs().getLastArg(options::OPT__SLASH_Fp)) {
4515 // FIXME: If anybody needs it, implement this obscure rule:
4516 // "If you specify a directory without a file name, the default file name
4517 // is VCx0.pch., where x is the major version of Visual C++ in use."
4518 Output = FpArg->getValue();
4519
4520 // "If you do not specify an extension as part of the path name, an
4521 // extension of .pch is assumed. "
4522 if (!llvm::sys::path::has_extension(Output))
4523 Output += ".pch";
4524 } else {
Mike Rice58df1af2018-09-11 17:10:44 +00004525 if (Arg *YcArg = C.getArgs().getLastArg(options::OPT__SLASH_Yc))
4526 Output = YcArg->getValue();
4527 if (Output.empty())
4528 Output = BaseName;
Nico Weber2ca4be92016-03-01 23:16:44 +00004529 llvm::sys::path::replace_extension(Output, ".pch");
4530 }
4531 return Output.str();
4532}
4533
Chandler Carruth2ad5de12012-01-25 11:01:57 +00004534const ToolChain &Driver::getToolChain(const ArgList &Args,
Artem Belevich959e0542015-07-10 19:47:55 +00004535 const llvm::Triple &Target) const {
Chandler Carruth2ad5de12012-01-25 11:01:57 +00004536
David Blaikie6ad71012017-01-13 18:53:43 +00004537 auto &TC = ToolChains[Target.str()];
Chandler Carruth2ad5de12012-01-25 11:01:57 +00004538 if (!TC) {
4539 switch (Target.getOS()) {
Reid Kleckner330fb172016-05-11 16:19:05 +00004540 case llvm::Triple::Haiku:
David Blaikie6ad71012017-01-13 18:53:43 +00004541 TC = llvm::make_unique<toolchains::Haiku>(*this, Target, Args);
Reid Kleckner330fb172016-05-11 16:19:05 +00004542 break;
Ed Schouten4dabea22017-06-25 08:29:09 +00004543 case llvm::Triple::Ananas:
4544 TC = llvm::make_unique<toolchains::Ananas>(*this, Target, Args);
4545 break;
Ed Schouten3c3e58c2015-03-26 11:13:44 +00004546 case llvm::Triple::CloudABI:
David Blaikie6ad71012017-01-13 18:53:43 +00004547 TC = llvm::make_unique<toolchains::CloudABI>(*this, Target, Args);
Ed Schouten3c3e58c2015-03-26 11:13:44 +00004548 break;
Chandler Carruth2ad5de12012-01-25 11:01:57 +00004549 case llvm::Triple::Darwin:
4550 case llvm::Triple::MacOSX:
4551 case llvm::Triple::IOS:
Tim Northover6f3ff222015-10-30 16:30:27 +00004552 case llvm::Triple::TvOS:
4553 case llvm::Triple::WatchOS:
David Blaikie6ad71012017-01-13 18:53:43 +00004554 TC = llvm::make_unique<toolchains::DarwinClang>(*this, Target, Args);
Chandler Carruth2ad5de12012-01-25 11:01:57 +00004555 break;
4556 case llvm::Triple::DragonFly:
David Blaikie6ad71012017-01-13 18:53:43 +00004557 TC = llvm::make_unique<toolchains::DragonFly>(*this, Target, Args);
Chandler Carruth2ad5de12012-01-25 11:01:57 +00004558 break;
4559 case llvm::Triple::OpenBSD:
David Blaikie6ad71012017-01-13 18:53:43 +00004560 TC = llvm::make_unique<toolchains::OpenBSD>(*this, Target, Args);
Chandler Carruth2ad5de12012-01-25 11:01:57 +00004561 break;
4562 case llvm::Triple::NetBSD:
David Blaikie6ad71012017-01-13 18:53:43 +00004563 TC = llvm::make_unique<toolchains::NetBSD>(*this, Target, Args);
Chandler Carruth2ad5de12012-01-25 11:01:57 +00004564 break;
4565 case llvm::Triple::FreeBSD:
David Blaikie6ad71012017-01-13 18:53:43 +00004566 TC = llvm::make_unique<toolchains::FreeBSD>(*this, Target, Args);
Chandler Carruth2ad5de12012-01-25 11:01:57 +00004567 break;
4568 case llvm::Triple::Minix:
David Blaikie6ad71012017-01-13 18:53:43 +00004569 TC = llvm::make_unique<toolchains::Minix>(*this, Target, Args);
Chandler Carruth2ad5de12012-01-25 11:01:57 +00004570 break;
4571 case llvm::Triple::Linux:
Andrey Turetskiy4798eb62016-06-16 10:36:09 +00004572 case llvm::Triple::ELFIAMCU:
Chandler Carruthcf705b22012-01-25 21:03:58 +00004573 if (Target.getArch() == llvm::Triple::hexagon)
David Blaikie6ad71012017-01-13 18:53:43 +00004574 TC = llvm::make_unique<toolchains::HexagonToolChain>(*this, Target,
4575 Args);
Vasileios Kalintirisc744e122015-11-12 15:26:54 +00004576 else if ((Target.getVendor() == llvm::Triple::MipsTechnologies) &&
4577 !Target.hasEnvironment())
David Blaikie6ad71012017-01-13 18:53:43 +00004578 TC = llvm::make_unique<toolchains::MipsLLVMToolChain>(*this, Target,
4579 Args);
Qiu Chaofan19828e32019-04-23 05:50:24 +00004580 else if (Target.getArch() == llvm::Triple::ppc ||
4581 Target.getArch() == llvm::Triple::ppc64 ||
4582 Target.getArch() == llvm::Triple::ppc64le)
4583 TC = llvm::make_unique<toolchains::PPCLinuxToolChain>(*this, Target,
4584 Args);
Chandler Carruthcf705b22012-01-25 21:03:58 +00004585 else
David Blaikie6ad71012017-01-13 18:53:43 +00004586 TC = llvm::make_unique<toolchains::Linux>(*this, Target, Args);
Chandler Carruth2ad5de12012-01-25 11:01:57 +00004587 break;
Derek Schuff6ab52fa2015-03-30 20:31:33 +00004588 case llvm::Triple::NaCl:
David Blaikie6ad71012017-01-13 18:53:43 +00004589 TC = llvm::make_unique<toolchains::NaClToolChain>(*this, Target, Args);
Derek Schuff6ab52fa2015-03-30 20:31:33 +00004590 break;
Petr Hosek62e1d232016-10-06 06:08:09 +00004591 case llvm::Triple::Fuchsia:
David Blaikie6ad71012017-01-13 18:53:43 +00004592 TC = llvm::make_unique<toolchains::Fuchsia>(*this, Target, Args);
Petr Hosek62e1d232016-10-06 06:08:09 +00004593 break;
David Chisnallf571cde2012-02-15 13:39:01 +00004594 case llvm::Triple::Solaris:
David Blaikie6ad71012017-01-13 18:53:43 +00004595 TC = llvm::make_unique<toolchains::Solaris>(*this, Target, Args);
David Chisnallf571cde2012-02-15 13:39:01 +00004596 break;
Tom Stellard8fa33092015-07-18 01:49:05 +00004597 case llvm::Triple::AMDHSA:
David Blaikie6ad71012017-01-13 18:53:43 +00004598 TC = llvm::make_unique<toolchains::AMDGPUToolChain>(*this, Target, Args);
Tom Stellard8fa33092015-07-18 01:49:05 +00004599 break;
Chandler Carruth2ad5de12012-01-25 11:01:57 +00004600 case llvm::Triple::Win32:
Saleem Abdulrasool377066a2014-03-27 22:50:18 +00004601 switch (Target.getEnvironment()) {
4602 default:
4603 if (Target.isOSBinFormatELF())
David Blaikie6ad71012017-01-13 18:53:43 +00004604 TC = llvm::make_unique<toolchains::Generic_ELF>(*this, Target, Args);
Saleem Abdulrasool377066a2014-03-27 22:50:18 +00004605 else if (Target.isOSBinFormatMachO())
David Blaikie6ad71012017-01-13 18:53:43 +00004606 TC = llvm::make_unique<toolchains::MachO>(*this, Target, Args);
Saleem Abdulrasool377066a2014-03-27 22:50:18 +00004607 else
David Blaikie6ad71012017-01-13 18:53:43 +00004608 TC = llvm::make_unique<toolchains::Generic_GCC>(*this, Target, Args);
Saleem Abdulrasool377066a2014-03-27 22:50:18 +00004609 break;
4610 case llvm::Triple::GNU:
David Blaikie6ad71012017-01-13 18:53:43 +00004611 TC = llvm::make_unique<toolchains::MinGW>(*this, Target, Args);
Saleem Abdulrasool377066a2014-03-27 22:50:18 +00004612 break;
Saleem Abdulrasool543a78b2014-10-24 03:13:37 +00004613 case llvm::Triple::Itanium:
David Blaikie6ad71012017-01-13 18:53:43 +00004614 TC = llvm::make_unique<toolchains::CrossWindowsToolChain>(*this, Target,
4615 Args);
Saleem Abdulrasool543a78b2014-10-24 03:13:37 +00004616 break;
Saleem Abdulrasool377066a2014-03-27 22:50:18 +00004617 case llvm::Triple::MSVC:
4618 case llvm::Triple::UnknownEnvironment:
Dave Leef96bedf2017-11-06 21:18:05 +00004619 if (Args.getLastArgValue(options::OPT_fuse_ld_EQ)
4620 .startswith_lower("bfd"))
4621 TC = llvm::make_unique<toolchains::CrossWindowsToolChain>(
4622 *this, Target, Args);
4623 else
4624 TC =
4625 llvm::make_unique<toolchains::MSVCToolChain>(*this, Target, Args);
Saleem Abdulrasool377066a2014-03-27 22:50:18 +00004626 break;
4627 }
Chandler Carruth2ad5de12012-01-25 11:01:57 +00004628 break;
Filipe Cabecinhasc888e192015-10-14 12:25:43 +00004629 case llvm::Triple::PS4:
David Blaikie6ad71012017-01-13 18:53:43 +00004630 TC = llvm::make_unique<toolchains::PS4CPU>(*this, Target, Args);
Filipe Cabecinhasc888e192015-10-14 12:25:43 +00004631 break;
David L Kreitzerd397ea42016-10-14 20:44:33 +00004632 case llvm::Triple::Contiki:
David Blaikie6ad71012017-01-13 18:53:43 +00004633 TC = llvm::make_unique<toolchains::Contiki>(*this, Target, Args);
David L Kreitzerd397ea42016-10-14 20:44:33 +00004634 break;
Kristina Brooks77a4adc2018-11-29 03:49:14 +00004635 case llvm::Triple::Hurd:
4636 TC = llvm::make_unique<toolchains::Hurd>(*this, Target, Args);
4637 break;
Chandler Carruth2ad5de12012-01-25 11:01:57 +00004638 default:
Douglas Katzman9f5e70e2015-05-26 18:01:33 +00004639 // Of these targets, Hexagon is the only one that might have
4640 // an OS of Linux, in which case it got handled above already.
Douglas Katzman15a63ed2015-08-12 18:36:12 +00004641 switch (Target.getArch()) {
4642 case llvm::Triple::tce:
David Blaikie6ad71012017-01-13 18:53:43 +00004643 TC = llvm::make_unique<toolchains::TCEToolChain>(*this, Target, Args);
Douglas Katzman15a63ed2015-08-12 18:36:12 +00004644 break;
Pekka Jaaskelainen67354482016-11-16 15:22:31 +00004645 case llvm::Triple::tcele:
David Blaikie6ad71012017-01-13 18:53:43 +00004646 TC = llvm::make_unique<toolchains::TCELEToolChain>(*this, Target, Args);
Pekka Jaaskelainen67354482016-11-16 15:22:31 +00004647 break;
Douglas Katzman15a63ed2015-08-12 18:36:12 +00004648 case llvm::Triple::hexagon:
David Blaikie6ad71012017-01-13 18:53:43 +00004649 TC = llvm::make_unique<toolchains::HexagonToolChain>(*this, Target,
4650 Args);
Douglas Katzman15a63ed2015-08-12 18:36:12 +00004651 break;
Jacques Pienaard964cc22016-03-28 21:02:54 +00004652 case llvm::Triple::lanai:
David Blaikie6ad71012017-01-13 18:53:43 +00004653 TC = llvm::make_unique<toolchains::LanaiToolChain>(*this, Target, Args);
Jacques Pienaard964cc22016-03-28 21:02:54 +00004654 break;
Douglas Katzman15a63ed2015-08-12 18:36:12 +00004655 case llvm::Triple::xcore:
David Blaikie6ad71012017-01-13 18:53:43 +00004656 TC = llvm::make_unique<toolchains::XCoreToolChain>(*this, Target, Args);
Douglas Katzman15a63ed2015-08-12 18:36:12 +00004657 break;
Dan Gohmanc2853072015-09-03 22:51:53 +00004658 case llvm::Triple::wasm32:
4659 case llvm::Triple::wasm64:
David Blaikie6ad71012017-01-13 18:53:43 +00004660 TC = llvm::make_unique<toolchains::WebAssembly>(*this, Target, Args);
Dan Gohmanc2853072015-09-03 22:51:53 +00004661 break;
Dylan McKay924fa3a2017-01-05 05:20:27 +00004662 case llvm::Triple::avr:
David Blaikie6ad71012017-01-13 18:53:43 +00004663 TC = llvm::make_unique<toolchains::AVRToolChain>(*this, Target, Args);
Dylan McKay924fa3a2017-01-05 05:20:27 +00004664 break;
Anton Korobeynikov93165d62019-01-15 19:44:05 +00004665 case llvm::Triple::msp430:
4666 TC =
4667 llvm::make_unique<toolchains::MSP430ToolChain>(*this, Target, Args);
4668 break;
David Bolvanskyf4be2532018-07-31 14:21:46 +00004669 case llvm::Triple::riscv32:
4670 case llvm::Triple::riscv64:
4671 TC = llvm::make_unique<toolchains::RISCVToolChain>(*this, Target, Args);
4672 break;
Douglas Katzman15a63ed2015-08-12 18:36:12 +00004673 default:
Douglas Katzmand6e597c2015-09-17 19:56:40 +00004674 if (Target.getVendor() == llvm::Triple::Myriad)
David Blaikie6ad71012017-01-13 18:53:43 +00004675 TC = llvm::make_unique<toolchains::MyriadToolChain>(*this, Target,
4676 Args);
Jonathan Roelofs901c7762017-05-25 15:42:13 +00004677 else if (toolchains::BareMetal::handlesTarget(Target))
4678 TC = llvm::make_unique<toolchains::BareMetal>(*this, Target, Args);
Douglas Katzmand6e597c2015-09-17 19:56:40 +00004679 else if (Target.isOSBinFormatELF())
David Blaikie6ad71012017-01-13 18:53:43 +00004680 TC = llvm::make_unique<toolchains::Generic_ELF>(*this, Target, Args);
Douglas Katzman15a63ed2015-08-12 18:36:12 +00004681 else if (Target.isOSBinFormatMachO())
David Blaikie6ad71012017-01-13 18:53:43 +00004682 TC = llvm::make_unique<toolchains::MachO>(*this, Target, Args);
Douglas Katzman15a63ed2015-08-12 18:36:12 +00004683 else
David Blaikie6ad71012017-01-13 18:53:43 +00004684 TC = llvm::make_unique<toolchains::Generic_GCC>(*this, Target, Args);
Douglas Katzman15a63ed2015-08-12 18:36:12 +00004685 }
Chandler Carruth2ad5de12012-01-25 11:01:57 +00004686 }
4687 }
Justin Lebar66c4fd72016-11-18 00:41:22 +00004688
4689 // Intentionally omitted from the switch above: llvm::Triple::CUDA. CUDA
4690 // compiles always need two toolchains, the CUDA toolchain and the host
4691 // toolchain. So the only valid way to create a CUDA toolchain is via
4692 // CreateOffloadingDeviceToolChains.
4693
Chandler Carruth2ad5de12012-01-25 11:01:57 +00004694 return *TC;
Daniel Dunbar4dff6a42009-03-10 23:41:59 +00004695}
Daniel Dunbar8fa879d2009-03-24 18:57:02 +00004696
Rafael Espindola2f69d402013-03-18 15:33:26 +00004697bool Driver::ShouldUseClangCompiler(const JobAction &JA) const {
Douglas Katzman00249092015-06-12 15:45:21 +00004698 // Say "no" if there is not exactly one input of a type clang understands.
Nico Weber5a459f82016-02-23 19:30:43 +00004699 if (JA.size() != 1 ||
4700 !types::isAcceptedByClang((*JA.input_begin())->getType()))
Nick Lewycky5cc9ebb2012-11-15 05:36:36 +00004701 return false;
4702
Douglas Katzman00249092015-06-12 15:45:21 +00004703 // And say "no" if this is not a kind of action clang understands.
Nick Lewycky5cc9ebb2012-11-15 05:36:36 +00004704 if (!isa<PreprocessJobAction>(JA) && !isa<PrecompileJobAction>(JA) &&
Bob Wilson23a55f12014-12-21 07:00:00 +00004705 !isa<CompileJobAction>(JA) && !isa<BackendJobAction>(JA))
Nick Lewycky5cc9ebb2012-11-15 05:36:36 +00004706 return false;
4707
4708 return true;
4709}
4710
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00004711/// GetReleaseVersion - Parse (([0-9]+)(.([0-9]+)(.([0-9]+)?))?)? and return the
4712/// grouped values as integers. Numbers which are not provided are set to 0.
Daniel Dunbarc7fd57a2009-03-26 15:58:36 +00004713///
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00004714/// \return True if the entire string was parsed (9.2), or all groups were
4715/// parsed (10.3.5extrastuff).
Mehdi Amini12011172016-10-06 05:11:48 +00004716bool Driver::GetReleaseVersion(StringRef Str, unsigned &Major, unsigned &Minor,
4717 unsigned &Micro, bool &HadExtra) {
Daniel Dunbarc7fd57a2009-03-26 15:58:36 +00004718 HadExtra = false;
4719
4720 Major = Minor = Micro = 0;
Mehdi Amini12011172016-10-06 05:11:48 +00004721 if (Str.empty())
Bob Wilson433cb312015-04-07 01:03:35 +00004722 return false;
Daniel Dunbarc7fd57a2009-03-26 15:58:36 +00004723
Mehdi Amini12011172016-10-06 05:11:48 +00004724 if (Str.consumeInteger(10, Major))
4725 return false;
4726 if (Str.empty())
Daniel Dunbarc7fd57a2009-03-26 15:58:36 +00004727 return true;
Mehdi Amini12011172016-10-06 05:11:48 +00004728 if (Str[0] != '.')
Daniel Dunbarc7fd57a2009-03-26 15:58:36 +00004729 return false;
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00004730
Mehdi Amini12011172016-10-06 05:11:48 +00004731 Str = Str.drop_front(1);
Daniel Dunbarc7fd57a2009-03-26 15:58:36 +00004732
Mehdi Amini12011172016-10-06 05:11:48 +00004733 if (Str.consumeInteger(10, Minor))
Daniel Dunbarc7fd57a2009-03-26 15:58:36 +00004734 return false;
Mehdi Amini12011172016-10-06 05:11:48 +00004735 if (Str.empty())
4736 return true;
4737 if (Str[0] != '.')
4738 return false;
4739 Str = Str.drop_front(1);
4740
4741 if (Str.consumeInteger(10, Micro))
4742 return false;
4743 if (!Str.empty())
4744 HadExtra = true;
Daniel Dunbarc7fd57a2009-03-26 15:58:36 +00004745 return true;
4746}
Hans Wennborg6ddc6902013-07-27 00:23:45 +00004747
Bruno Cardoso Lopes8ed5cac2016-03-31 02:45:46 +00004748/// Parse digits from a string \p Str and fulfill \p Digits with
4749/// the parsed numbers. This method assumes that the max number of
4750/// digits to look for is equal to Digits.size().
4751///
4752/// \return True if the entire string was parsed and there are
4753/// no extra characters remaining at the end.
Mehdi Amini12011172016-10-06 05:11:48 +00004754bool Driver::GetReleaseVersion(StringRef Str,
Bruno Cardoso Lopes8ed5cac2016-03-31 02:45:46 +00004755 MutableArrayRef<unsigned> Digits) {
Mehdi Amini12011172016-10-06 05:11:48 +00004756 if (Str.empty())
Bruno Cardoso Lopes8ed5cac2016-03-31 02:45:46 +00004757 return false;
4758
Bruno Cardoso Lopes8ed5cac2016-03-31 02:45:46 +00004759 unsigned CurDigit = 0;
4760 while (CurDigit < Digits.size()) {
Mehdi Amini12011172016-10-06 05:11:48 +00004761 unsigned Digit;
4762 if (Str.consumeInteger(10, Digit))
Bruno Cardoso Lopes8ed5cac2016-03-31 02:45:46 +00004763 return false;
Mehdi Amini12011172016-10-06 05:11:48 +00004764 Digits[CurDigit] = Digit;
4765 if (Str.empty())
4766 return true;
4767 if (Str[0] != '.')
4768 return false;
4769 Str = Str.drop_front(1);
Bruno Cardoso Lopes8ed5cac2016-03-31 02:45:46 +00004770 CurDigit++;
4771 }
4772
4773 // More digits than requested, bail out...
4774 return false;
4775}
4776
Simon Atanasyan27c0f202019-04-02 18:03:15 +00004777std::pair<unsigned, unsigned>
4778Driver::getIncludeExcludeOptionFlagMasks(bool IsClCompatMode) const {
Hans Wennborg6ddc6902013-07-27 00:23:45 +00004779 unsigned IncludedFlagsBitmask = 0;
Rafael Espindolacc707bc2013-09-25 15:54:41 +00004780 unsigned ExcludedFlagsBitmask = options::NoDriverOption;
Hans Wennborg6ddc6902013-07-27 00:23:45 +00004781
Hans Wennborg797004d2018-11-08 11:27:04 +00004782 if (IsClCompatMode) {
Hans Wennborg19076102013-07-31 20:51:53 +00004783 // Include CL and Core options.
4784 IncludedFlagsBitmask |= options::CLOption;
4785 IncludedFlagsBitmask |= options::CoreOption;
Hans Wennborg6ddc6902013-07-27 00:23:45 +00004786 } else {
4787 ExcludedFlagsBitmask |= options::CLOption;
4788 }
4789
4790 return std::make_pair(IncludedFlagsBitmask, ExcludedFlagsBitmask);
4791}
Benjamin Kramerab88f622014-03-25 18:02:07 +00004792
Douglas Katzmanf08fadf2015-06-04 14:40:44 +00004793bool clang::driver::isOptimizationLevelFast(const ArgList &Args) {
Benjamin Kramerab88f622014-03-25 18:02:07 +00004794 return Args.hasFlag(options::OPT_Ofast, options::OPT_O_Group, false);
4795}