blob: e48dac26bb65a5cd6d7a1455ffa1752376797213 [file] [log] [blame]
Nick Lewyckye47c2452010-09-23 23:48:20 +00001//===--- Driver.cpp - Clang GCC Compatible Driver -------------------------===//
Daniel Dunbar544ecd12009-03-02 19:59:07 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
Daniel Dunbar544ecd12009-03-02 19:59:07 +000010#include "clang/Driver/Driver.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000011#include "InputInfo.h"
David L. Jonesf561aba2017-03-08 01:02:16 +000012#include "ToolChains/AMDGPU.h"
13#include "ToolChains/AVR.h"
Ed Schouten4dabea22017-06-25 08:29:09 +000014#include "ToolChains/Ananas.h"
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"
Jonathan Roelofs901c7762017-05-25 15:42:13 +000025#include "ToolChains/BareMetal.h"
David L. Jonesf561aba2017-03-08 01:02:16 +000026#include "ToolChains/Haiku.h"
27#include "ToolChains/Hexagon.h"
28#include "ToolChains/Lanai.h"
29#include "ToolChains/Linux.h"
30#include "ToolChains/MinGW.h"
31#include "ToolChains/Minix.h"
Konstantin Zhuravlyove37b32c2017-03-08 22:36:04 +000032#include "ToolChains/MipsLinux.h"
David L. Jonesf561aba2017-03-08 01:02:16 +000033#include "ToolChains/MSVC.h"
34#include "ToolChains/Myriad.h"
35#include "ToolChains/NaCl.h"
36#include "ToolChains/NetBSD.h"
37#include "ToolChains/OpenBSD.h"
38#include "ToolChains/PS4CPU.h"
39#include "ToolChains/Solaris.h"
40#include "ToolChains/TCE.h"
41#include "ToolChains/WebAssembly.h"
42#include "ToolChains/XCore.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000043#include "clang/Basic/Version.h"
Benjamin Kramerd45b2052015-10-07 15:48:01 +000044#include "clang/Basic/VirtualFileSystem.h"
Alp Toker1d257e12014-06-04 03:28:55 +000045#include "clang/Config/config.h"
Daniel Dunbar1688f1a2009-03-12 07:58:46 +000046#include "clang/Driver/Action.h"
Daniel Dunbarb2cd66b2009-03-04 20:49:20 +000047#include "clang/Driver/Compilation.h"
Daniel Dunbarc0b3e952009-03-12 08:55:43 +000048#include "clang/Driver/DriverDiagnostic.h"
Daniel Dunbare75d8342009-03-16 06:56:51 +000049#include "clang/Driver/Job.h"
Daniel Dunbarb2cd66b2009-03-04 20:49:20 +000050#include "clang/Driver/Options.h"
Peter Collingbournea4ccff32015-02-20 20:30:56 +000051#include "clang/Driver/SanitizerArgs.h"
Daniel Dunbare75d8342009-03-16 06:56:51 +000052#include "clang/Driver/Tool.h"
53#include "clang/Driver/ToolChain.h"
Chris Lattnerce6c42f2011-03-23 04:04:01 +000054#include "llvm/ADT/ArrayRef.h"
Hans Wennborg6ddc6902013-07-27 00:23:45 +000055#include "llvm/ADT/STLExtras.h"
Justin Lebar62907612016-07-06 21:21:39 +000056#include "llvm/ADT/SmallSet.h"
Hans Wennborg23d26a32014-06-18 17:21:50 +000057#include "llvm/ADT/StringExtras.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000058#include "llvm/ADT/StringSet.h"
Hans Wennborg70850d82013-07-18 20:29:38 +000059#include "llvm/ADT/StringSwitch.h"
Nico Weberd637c052018-04-30 13:52:15 +000060#include "llvm/Config/llvm-config.h"
Reid Kleckner898229a2013-06-14 17:17:23 +000061#include "llvm/Option/Arg.h"
62#include "llvm/Option/ArgList.h"
Chandler Carruth5553d0d2014-01-07 11:51:46 +000063#include "llvm/Option/OptSpecifier.h"
Reid Kleckner898229a2013-06-14 17:17:23 +000064#include "llvm/Option/OptTable.h"
65#include "llvm/Option/Option.h"
Serge Pavlov208ac652018-01-01 13:27:01 +000066#include "llvm/Support/CommandLine.h"
David Blaikie79000202011-09-23 05:57:42 +000067#include "llvm/Support/ErrorHandling.h"
Michael J. Spencerf28df4c2010-12-17 21:22:22 +000068#include "llvm/Support/FileSystem.h"
Michael J. Spencer8aaf4992010-11-29 18:12:39 +000069#include "llvm/Support/Path.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000070#include "llvm/Support/PrettyStackTrace.h"
Hans Wennborg23d26a32014-06-18 17:21:50 +000071#include "llvm/Support/Process.h"
Michael J. Spencer8aaf4992010-11-29 18:12:39 +000072#include "llvm/Support/Program.h"
Dimitry Andric81c40422017-06-06 21:54:21 +000073#include "llvm/Support/TargetRegistry.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000074#include "llvm/Support/raw_ostream.h"
Serge Pavlov208ac652018-01-01 13:27:01 +000075#include "llvm/Support/StringSaver.h"
Dylan Noblesmith4f4e7452012-02-02 00:40:14 +000076#include <map>
Ahmed Charlesdfca6f92014-03-09 11:36:40 +000077#include <memory>
Benjamin Kramercfeacf52016-05-27 14:27:13 +000078#include <utility>
Bruno Cardoso Lopes02681c42016-11-17 21:41:22 +000079#if LLVM_ON_UNIX
80#include <unistd.h> // getpid
81#endif
Dylan Noblesmith86780e92012-02-01 14:25:28 +000082
Daniel Dunbarb2cd66b2009-03-04 20:49:20 +000083using namespace clang::driver;
Chris Lattnerada1c912009-03-26 05:56:24 +000084using namespace clang;
Reid Kleckner898229a2013-06-14 17:17:23 +000085using namespace llvm::opt;
Daniel Dunbarb2cd66b2009-03-04 20:49:20 +000086
Petr Hosekdd38d932018-05-29 22:35:39 +000087Driver::Driver(StringRef ClangExecutable, StringRef TargetTriple,
Benjamin Kramerd45b2052015-10-07 15:48:01 +000088 DiagnosticsEngine &Diags,
89 IntrusiveRefCntPtr<vfs::FileSystem> VFS)
Benjamin Kramercfeacf52016-05-27 14:27:13 +000090 : Opts(createDriverOptTable()), Diags(Diags), VFS(std::move(VFS)),
91 Mode(GCCMode), SaveTemps(SaveTempsNone), BitcodeEmbed(EmbedNone),
92 LTOMode(LTOK_None), ClangExecutable(ClangExecutable),
Alex Lorenz045c5142018-04-07 00:03:27 +000093 SysRoot(DEFAULT_SYSROOT), DriverTitle("clang LLVM compiler"),
94 CCPrintOptionsFilename(nullptr), CCPrintHeadersFilename(nullptr),
95 CCLogDiagnosticsFilename(nullptr), CCCPrintBindings(false),
96 CCPrintOptions(false), CCPrintHeaders(false), CCLogDiagnostics(false),
Petr Hosekdd38d932018-05-29 22:35:39 +000097 CCGenDiagnostics(false), TargetTriple(TargetTriple),
Alex Lorenz045c5142018-04-07 00:03:27 +000098 CCCGenericGCCName(""), Saver(Alloc), CheckInputsExist(true),
99 CCCUsePCH(true), GenReproducer(false),
100 SuppressMissingInputWarning(false) {
Daniel Dunbar3f3e2cd2010-01-20 02:35:16 +0000101
Benjamin Kramerd45b2052015-10-07 15:48:01 +0000102 // Provide a sane fallback if no VFS is specified.
103 if (!this->VFS)
104 this->VFS = vfs::getRealFileSystem();
105
Sumanth Gundapaneni3a1592942015-03-03 20:43:12 +0000106 Name = llvm::sys::path::filename(ClangExecutable);
Douglas Katzmana67e50c2015-06-26 15:47:46 +0000107 Dir = llvm::sys::path::parent_path(ClangExecutable);
Benjamin Kramerf420dda2015-10-13 15:19:32 +0000108 InstalledDir = Dir; // Provide a sensible default installed dir.
Bob Wilsona20a1da2013-03-23 05:17:59 +0000109
Serge Pavlov208ac652018-01-01 13:27:01 +0000110#if defined(CLANG_CONFIG_FILE_SYSTEM_DIR)
111 SystemConfigDir = CLANG_CONFIG_FILE_SYSTEM_DIR;
112#endif
113#if defined(CLANG_CONFIG_FILE_USER_DIR)
114 UserConfigDir = CLANG_CONFIG_FILE_USER_DIR;
115#endif
116
Bob Wilsona20a1da2013-03-23 05:17:59 +0000117 // Compute the path to the resource directory.
118 StringRef ClangResourceDir(CLANG_RESOURCE_DIR);
119 SmallString<128> P(Dir);
Chandler Carruthfd3cc702014-12-29 12:09:08 +0000120 if (ClangResourceDir != "") {
Bob Wilsona20a1da2013-03-23 05:17:59 +0000121 llvm::sys::path::append(P, ClangResourceDir);
Chandler Carruthfd3cc702014-12-29 12:09:08 +0000122 } else {
123 StringRef ClangLibdirSuffix(CLANG_LIBDIR_SUFFIX);
Argyrios Kyrtzidisbcae0472017-02-25 18:14:35 +0000124 P = llvm::sys::path::parent_path(Dir);
125 llvm::sys::path::append(P, Twine("lib") + ClangLibdirSuffix, "clang",
Chandler Carruthfd3cc702014-12-29 12:09:08 +0000126 CLANG_VERSION_STRING);
127 }
Bob Wilsona20a1da2013-03-23 05:17:59 +0000128 ResourceDir = P.str();
Daniel Dunbar544ecd12009-03-02 19:59:07 +0000129}
130
Zachary Turneraff19c32016-08-12 17:47:52 +0000131void Driver::ParseDriverMode(StringRef ProgramName,
132 ArrayRef<const char *> Args) {
Martin Storsjo1fab23d2018-04-25 21:23:59 +0000133 if (ClangNameParts.isEmpty())
134 ClangNameParts = ToolChain::getTargetAndModeFromProgramName(ProgramName);
Serge Pavlov4e769842017-08-29 05:22:26 +0000135 setDriverModeFromOption(ClangNameParts.DriverMode);
Hans Wennborg70850d82013-07-18 20:29:38 +0000136
Douglas Katzman6bbffc42015-06-25 18:51:37 +0000137 for (const char *ArgPtr : Args) {
Erich Keane258f0592018-02-07 00:19:58 +0000138 // Ignore nullptrs, they are the response file's EOL markers.
Douglas Katzman6bbffc42015-06-25 18:51:37 +0000139 if (ArgPtr == nullptr)
Reid Kleckneraf5fd6a2014-08-22 19:29:30 +0000140 continue;
Douglas Katzman6bbffc42015-06-25 18:51:37 +0000141 const StringRef Arg = ArgPtr;
Zachary Turneraff19c32016-08-12 17:47:52 +0000142 setDriverModeFromOption(Arg);
Hans Wennborg70850d82013-07-18 20:29:38 +0000143 }
144}
145
Zachary Turneraff19c32016-08-12 17:47:52 +0000146void Driver::setDriverModeFromOption(StringRef Opt) {
147 const std::string OptName =
148 getOpts().getOption(options::OPT_driver_mode).getPrefixedName();
149 if (!Opt.startswith(OptName))
150 return;
151 StringRef Value = Opt.drop_front(OptName.size());
152
Erich Keane2908a042018-02-12 17:47:01 +0000153 if (auto M = llvm::StringSwitch<llvm::Optional<DriverMode>>(Value)
154 .Case("gcc", GCCMode)
155 .Case("g++", GXXMode)
156 .Case("cpp", CPPMode)
157 .Case("cl", CLMode)
158 .Default(None))
159 Mode = *M;
Zachary Turneraff19c32016-08-12 17:47:52 +0000160 else
161 Diag(diag::err_drv_unsupported_option_argument) << OptName << Value;
162}
163
Benjamin Kramer43c0f482017-06-30 13:21:27 +0000164InputArgList Driver::ParseArgStrings(ArrayRef<const char *> ArgStrings,
165 bool &ContainsError) {
Daniel Dunbar2608c542009-03-18 01:38:48 +0000166 llvm::PrettyStackTraceString CrashInfo("Command line argument parsing");
Benjamin Kramer43c0f482017-06-30 13:21:27 +0000167 ContainsError = false;
Hans Wennborg6ddc6902013-07-27 00:23:45 +0000168
169 unsigned IncludedFlagsBitmask;
170 unsigned ExcludedFlagsBitmask;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +0000171 std::tie(IncludedFlagsBitmask, ExcludedFlagsBitmask) =
Douglas Katzmana67e50c2015-06-26 15:47:46 +0000172 getIncludeExcludeOptionFlagMasks();
Hans Wennborg6ddc6902013-07-27 00:23:45 +0000173
Daniel Dunbar52ed5fe2009-11-19 06:35:06 +0000174 unsigned MissingArgIndex, MissingArgCount;
David Blaikie69a1d8c2015-06-22 22:07:27 +0000175 InputArgList Args =
David Blaikie6d492ad2015-06-21 06:32:36 +0000176 getOpts().ParseArgs(ArgStrings, MissingArgIndex, MissingArgCount,
177 IncludedFlagsBitmask, ExcludedFlagsBitmask);
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +0000178
Daniel Dunbar52ed5fe2009-11-19 06:35:06 +0000179 // Check for missing argument error.
Benjamin Kramer43c0f482017-06-30 13:21:27 +0000180 if (MissingArgCount) {
181 Diag(diag::err_drv_missing_argument)
David Blaikie69a1d8c2015-06-22 22:07:27 +0000182 << Args.getArgString(MissingArgIndex) << MissingArgCount;
Benjamin Kramer43c0f482017-06-30 13:21:27 +0000183 ContainsError |=
184 Diags.getDiagnosticLevel(diag::err_drv_missing_argument,
185 SourceLocation()) > DiagnosticsEngine::Warning;
186 }
Daniel Dunbar65229332009-03-13 11:38:42 +0000187
Daniel Dunbar52ed5fe2009-11-19 06:35:06 +0000188 // Check for unsupported options.
David Blaikie69a1d8c2015-06-22 22:07:27 +0000189 for (const Arg *A : Args) {
Michael J. Spencer66e2b202012-10-19 22:37:06 +0000190 if (A->getOption().hasFlag(options::Unsupported)) {
Brian Gesiak24910762018-01-06 00:25:40 +0000191 unsigned DiagID;
192 auto ArgString = A->getAsString(Args);
193 std::string Nearest;
194 if (getOpts().findNearest(
195 ArgString, Nearest, IncludedFlagsBitmask,
196 ExcludedFlagsBitmask | options::Unsupported) > 1) {
197 DiagID = diag::err_drv_unsupported_opt;
198 Diag(DiagID) << ArgString;
199 } else {
200 DiagID = diag::err_drv_unsupported_opt_with_suggestion;
201 Diag(DiagID) << ArgString << Nearest;
202 }
203 ContainsError |= Diags.getDiagnosticLevel(DiagID, SourceLocation()) >
Benjamin Kramer43c0f482017-06-30 13:21:27 +0000204 DiagnosticsEngine::Warning;
Daniel Dunbard8500f32009-03-22 23:26:43 +0000205 continue;
206 }
Chad Rosierce975d92012-02-22 17:55:22 +0000207
208 // Warn about -mcpu= without an argument.
Douglas Katzmana67e50c2015-06-26 15:47:46 +0000209 if (A->getOption().matches(options::OPT_mcpu_EQ) && A->containsValue("")) {
Benjamin Kramer43c0f482017-06-30 13:21:27 +0000210 Diag(diag::warn_drv_empty_joined_argument) << A->getAsString(Args);
211 ContainsError |= Diags.getDiagnosticLevel(
212 diag::warn_drv_empty_joined_argument,
213 SourceLocation()) > DiagnosticsEngine::Warning;
Chad Rosierce975d92012-02-22 17:55:22 +0000214 }
Daniel Dunbard02cb1d2009-03-05 06:38:47 +0000215 }
216
Benjamin Kramer43c0f482017-06-30 13:21:27 +0000217 for (const Arg *A : Args.filtered(options::OPT_UNKNOWN)) {
Brian Gesiak24910762018-01-06 00:25:40 +0000218 unsigned DiagID;
219 auto ArgString = A->getAsString(Args);
220 std::string Nearest;
221 if (getOpts().findNearest(
222 ArgString, Nearest, IncludedFlagsBitmask, ExcludedFlagsBitmask) > 1) {
223 DiagID = IsCLMode() ? diag::warn_drv_unknown_argument_clang_cl
224 : diag::err_drv_unknown_argument;
225 Diags.Report(DiagID) << ArgString;
226 } else {
227 DiagID = IsCLMode() ? diag::warn_drv_unknown_argument_clang_cl_with_suggestion
228 : diag::err_drv_unknown_argument_with_suggestion;
229 Diags.Report(DiagID) << ArgString << Nearest;
230 }
231 ContainsError |= Diags.getDiagnosticLevel(DiagID, SourceLocation()) >
Benjamin Kramer43c0f482017-06-30 13:21:27 +0000232 DiagnosticsEngine::Warning;
233 }
Rafael Espindola8a2d4962013-09-23 23:55:25 +0000234
Daniel Dunbard02cb1d2009-03-05 06:38:47 +0000235 return Args;
236}
237
Chad Rosier7742b5d2011-07-27 23:36:45 +0000238// Determine which compilation mode we are in. We look for options which
239// affect the phase, starting with the earliest phases, and record which
240// option we used to determine the final phase.
Douglas Katzmana67e50c2015-06-26 15:47:46 +0000241phases::ID Driver::getFinalPhase(const DerivedArgList &DAL,
242 Arg **FinalPhaseArg) const {
Craig Topper92fc2df2014-05-17 16:56:41 +0000243 Arg *PhaseArg = nullptr;
Chad Rosier7742b5d2011-07-27 23:36:45 +0000244 phases::ID FinalPhase;
Eric Christopherf901e852011-08-17 22:59:59 +0000245
Hans Wennborge50cec32014-06-13 20:59:54 +0000246 // -{E,EP,P,M,MM} only run the preprocessor.
Douglas Katzmana67e50c2015-06-26 15:47:46 +0000247 if (CCCIsCPP() || (PhaseArg = DAL.getLastArg(options::OPT_E)) ||
Hans Wennborge50cec32014-06-13 20:59:54 +0000248 (PhaseArg = DAL.getLastArg(options::OPT__SLASH_EP)) ||
Hans Wennborge0053472013-12-20 18:40:46 +0000249 (PhaseArg = DAL.getLastArg(options::OPT_M, options::OPT_MM)) ||
250 (PhaseArg = DAL.getLastArg(options::OPT__SLASH_P))) {
Chad Rosier7742b5d2011-07-27 23:36:45 +0000251 FinalPhase = phases::Preprocess;
Eric Christopherf901e852011-08-17 22:59:59 +0000252
Richard Smithdd4ad3d2016-08-30 19:06:26 +0000253 // --precompile only runs up to precompilation.
254 } else if ((PhaseArg = DAL.getLastArg(options::OPT__precompile))) {
255 FinalPhase = phases::Precompile;
256
Bob Wilson23a55f12014-12-21 07:00:00 +0000257 // -{fsyntax-only,-analyze,emit-ast} only run up to the compiler.
Chad Rosier7742b5d2011-07-27 23:36:45 +0000258 } else if ((PhaseArg = DAL.getLastArg(options::OPT_fsyntax_only)) ||
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +0000259 (PhaseArg = DAL.getLastArg(options::OPT_module_file_info)) ||
Ben Langmuir2cb4a782014-02-05 22:21:15 +0000260 (PhaseArg = DAL.getLastArg(options::OPT_verify_pch)) ||
Chad Rosier7742b5d2011-07-27 23:36:45 +0000261 (PhaseArg = DAL.getLastArg(options::OPT_rewrite_objc)) ||
Fariborz Jahanian73223bb2012-04-02 15:59:19 +0000262 (PhaseArg = DAL.getLastArg(options::OPT_rewrite_legacy_objc)) ||
Ted Kremenekf7639e12012-03-06 20:06:33 +0000263 (PhaseArg = DAL.getLastArg(options::OPT__migrate)) ||
Chad Rosier7742b5d2011-07-27 23:36:45 +0000264 (PhaseArg = DAL.getLastArg(options::OPT__analyze,
Chad Rosier1aeb15a2012-03-06 23:14:35 +0000265 options::OPT__analyze_auto)) ||
Bob Wilson23a55f12014-12-21 07:00:00 +0000266 (PhaseArg = DAL.getLastArg(options::OPT_emit_ast))) {
Chad Rosier7742b5d2011-07-27 23:36:45 +0000267 FinalPhase = phases::Compile;
268
Bob Wilson23a55f12014-12-21 07:00:00 +0000269 // -S only runs up to the backend.
270 } else if ((PhaseArg = DAL.getLastArg(options::OPT_S))) {
271 FinalPhase = phases::Backend;
272
Artem Belevich4242f412015-07-28 21:01:21 +0000273 // -c compilation only runs up to the assembler.
274 } else if ((PhaseArg = DAL.getLastArg(options::OPT_c))) {
Chad Rosier7742b5d2011-07-27 23:36:45 +0000275 FinalPhase = phases::Assemble;
276
277 // Otherwise do everything.
278 } else
279 FinalPhase = phases::Link;
280
281 if (FinalPhaseArg)
282 *FinalPhaseArg = PhaseArg;
283
284 return FinalPhase;
285}
286
David Blaikie0aaa7622017-01-13 17:34:15 +0000287static Arg *MakeInputArg(DerivedArgList &Args, OptTable &Opts,
Martin Storsjo665c7a42018-05-04 06:05:58 +0000288 StringRef Value, bool Claim = true) {
David Blaikie0aaa7622017-01-13 17:34:15 +0000289 Arg *A = new Arg(Opts.getOption(options::OPT_INPUT), Value,
Hans Wennborged1d0722013-08-13 21:32:29 +0000290 Args.getBaseArgs().MakeIndex(Value), Value.data());
Hans Wennborg55362852014-05-02 22:55:30 +0000291 Args.AddSynthesizedArg(A);
Martin Storsjo665c7a42018-05-04 06:05:58 +0000292 if (Claim)
293 A->claim();
Hans Wennborged1d0722013-08-13 21:32:29 +0000294 return A;
295}
296
Daniel Dunbar775d4062010-06-11 22:00:26 +0000297DerivedArgList *Driver::TranslateInputArgs(const InputArgList &Args) const {
298 DerivedArgList *DAL = new DerivedArgList(Args);
299
Daniel Dunbar2cc3f172010-09-17 00:45:02 +0000300 bool HasNostdlib = Args.hasArg(options::OPT_nostdlib);
Nirav Daveb0bb6142015-11-24 16:07:21 +0000301 bool HasNodefaultlib = Args.hasArg(options::OPT_nodefaultlibs);
Saleem Abdulrasool688b6bc2014-12-29 19:01:36 +0000302 for (Arg *A : Args) {
Daniel Dunbarfb3d7472010-06-14 21:23:12 +0000303 // Unfortunately, we have to parse some forwarding options (-Xassembler,
304 // -Xlinker, -Xpreprocessor) because we either integrate their functionality
305 // (assembler and preprocessor), or bypass a previous driver ('collect2').
Daniel Dunbar5a9d1832010-06-14 21:37:09 +0000306
307 // Rewrite linker options, to replace --no-demangle with a custom internal
308 // option.
309 if ((A->getOption().matches(options::OPT_Wl_COMMA) ||
310 A->getOption().matches(options::OPT_Xlinker)) &&
311 A->containsValue("--no-demangle")) {
Daniel Dunbarfb3d7472010-06-14 21:23:12 +0000312 // Add the rewritten no-demangle argument.
313 DAL->AddFlagArg(A, Opts->getOption(options::OPT_Z_Xlinker__no_demangle));
314
315 // Add the remaining values as Xlinker arguments.
Benjamin Kramer72e64312015-09-24 14:48:49 +0000316 for (StringRef Val : A->getValues())
Douglas Katzmana34b7bf2015-06-30 19:32:57 +0000317 if (Val != "--no-demangle")
318 DAL->AddSeparateArg(A, Opts->getOption(options::OPT_Xlinker), Val);
Daniel Dunbarfb3d7472010-06-14 21:23:12 +0000319
320 continue;
321 }
322
Daniel Dunbar5a9d1832010-06-14 21:37:09 +0000323 // Rewrite preprocessor options, to replace -Wp,-MD,FOO which is used by
324 // some build systems. We don't try to be complete here because we don't
325 // care to encourage this usage model.
326 if (A->getOption().matches(options::OPT_Wp_COMMA) &&
Richard Smithbd55daf2012-11-01 04:30:05 +0000327 (A->getValue(0) == StringRef("-MD") ||
328 A->getValue(0) == StringRef("-MMD"))) {
Daniel Dunbar3648ba72010-06-15 20:30:18 +0000329 // Rewrite to -MD/-MMD along with -MF.
Richard Smithbd55daf2012-11-01 04:30:05 +0000330 if (A->getValue(0) == StringRef("-MD"))
Daniel Dunbar3648ba72010-06-15 20:30:18 +0000331 DAL->AddFlagArg(A, Opts->getOption(options::OPT_MD));
332 else
333 DAL->AddFlagArg(A, Opts->getOption(options::OPT_MMD));
Michael J. Spencer70d85be2012-11-07 23:37:14 +0000334 if (A->getNumValues() == 2)
335 DAL->AddSeparateArg(A, Opts->getOption(options::OPT_MF),
336 A->getValue(1));
Daniel Dunbar5a9d1832010-06-14 21:37:09 +0000337 continue;
338 }
339
Shantonu Senafeb03b2010-09-17 18:39:08 +0000340 // Rewrite reserved library names.
341 if (A->getOption().matches(options::OPT_l)) {
Richard Smithbd55daf2012-11-01 04:30:05 +0000342 StringRef Value = A->getValue();
Daniel Dunbar2cc3f172010-09-17 00:45:02 +0000343
Shantonu Senafeb03b2010-09-17 18:39:08 +0000344 // Rewrite unless -nostdlib is present.
Nirav Daveb0bb6142015-11-24 16:07:21 +0000345 if (!HasNostdlib && !HasNodefaultlib && Value == "stdc++") {
Douglas Katzmana67e50c2015-06-26 15:47:46 +0000346 DAL->AddFlagArg(A, Opts->getOption(options::OPT_Z_reserved_lib_stdcxx));
Daniel Dunbar2cc3f172010-09-17 00:45:02 +0000347 continue;
348 }
Shantonu Senafeb03b2010-09-17 18:39:08 +0000349
350 // Rewrite unconditionally.
351 if (Value == "cc_kext") {
Douglas Katzmana67e50c2015-06-26 15:47:46 +0000352 DAL->AddFlagArg(A, Opts->getOption(options::OPT_Z_reserved_lib_cckext));
Shantonu Senafeb03b2010-09-17 18:39:08 +0000353 continue;
354 }
Daniel Dunbar2cc3f172010-09-17 00:45:02 +0000355 }
356
Hans Wennborged1d0722013-08-13 21:32:29 +0000357 // Pick up inputs via the -- option.
358 if (A->getOption().matches(options::OPT__DASH_DASH)) {
359 A->claim();
Benjamin Kramer72e64312015-09-24 14:48:49 +0000360 for (StringRef Val : A->getValues())
Martin Storsjo665c7a42018-05-04 06:05:58 +0000361 DAL->append(MakeInputArg(*DAL, *Opts, Val, false));
Hans Wennborged1d0722013-08-13 21:32:29 +0000362 continue;
363 }
364
Saleem Abdulrasool688b6bc2014-12-29 19:01:36 +0000365 DAL->append(A);
Daniel Dunbarfb3d7472010-06-14 21:23:12 +0000366 }
Daniel Dunbar775d4062010-06-11 22:00:26 +0000367
Andrey Turetskiy6a8b91d2016-04-21 10:16:48 +0000368 // Enforce -static if -miamcu is present.
Andrey Turetskiy5fea71c2016-06-29 10:57:17 +0000369 if (Args.hasFlag(options::OPT_miamcu, options::OPT_mno_iamcu, false))
370 DAL->AddFlagArg(0, Opts->getOption(options::OPT_static));
Andrey Turetskiy6a8b91d2016-04-21 10:16:48 +0000371
Douglas Katzmana67e50c2015-06-26 15:47:46 +0000372// Add a default value of -mlinker-version=, if one was given and the user
373// didn't specify one.
Daniel Dunbar628fcf42010-08-12 00:05:12 +0000374#if defined(HOST_LINK_VERSION)
Tim Northover018578c2015-06-12 19:21:35 +0000375 if (!Args.hasArg(options::OPT_mlinker_version_EQ) &&
376 strlen(HOST_LINK_VERSION) > 0) {
Daniel Dunbar628fcf42010-08-12 00:05:12 +0000377 DAL->AddJoinedArg(0, Opts->getOption(options::OPT_mlinker_version_EQ),
378 HOST_LINK_VERSION);
Daniel Dunbarb613ffc2010-08-17 22:32:45 +0000379 DAL->getLastArg(options::OPT_mlinker_version_EQ)->claim();
Daniel Dunbar628fcf42010-08-12 00:05:12 +0000380 }
381#endif
382
Daniel Dunbar775d4062010-06-11 22:00:26 +0000383 return DAL;
384}
385
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000386/// Compute target triple from args.
Artem Belevich959e0542015-07-10 19:47:55 +0000387///
388/// This routine provides the logic to compute a target triple from various
389/// args passed to the driver and the default triple string.
Andrey Turetskiy6a8b91d2016-04-21 10:16:48 +0000390static llvm::Triple computeTargetTriple(const Driver &D,
Petr Hosekdd38d932018-05-29 22:35:39 +0000391 StringRef TargetTriple,
Artem Belevich959e0542015-07-10 19:47:55 +0000392 const ArgList &Args,
393 StringRef DarwinArchName = "") {
394 // FIXME: Already done in Compilation *Driver::BuildCompilation
395 if (const Arg *A = Args.getLastArg(options::OPT_target))
Petr Hosekdd38d932018-05-29 22:35:39 +0000396 TargetTriple = A->getValue();
Artem Belevich959e0542015-07-10 19:47:55 +0000397
Petr Hosekdd38d932018-05-29 22:35:39 +0000398 llvm::Triple Target(llvm::Triple::normalize(TargetTriple));
Artem Belevich959e0542015-07-10 19:47:55 +0000399
400 // Handle Apple-specific options available here.
401 if (Target.isOSBinFormatMachO()) {
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +0000402 // If an explicit Darwin arch name is given, that trumps all.
Artem Belevich959e0542015-07-10 19:47:55 +0000403 if (!DarwinArchName.empty()) {
404 tools::darwin::setTripleTypeForMachOArchName(Target, DarwinArchName);
405 return Target;
406 }
407
408 // Handle the Darwin '-arch' flag.
409 if (Arg *A = Args.getLastArg(options::OPT_arch)) {
410 StringRef ArchName = A->getValue();
411 tools::darwin::setTripleTypeForMachOArchName(Target, ArchName);
412 }
413 }
414
415 // Handle pseudo-target flags '-mlittle-endian'/'-EL' and
416 // '-mbig-endian'/'-EB'.
417 if (Arg *A = Args.getLastArg(options::OPT_mlittle_endian,
418 options::OPT_mbig_endian)) {
419 if (A->getOption().matches(options::OPT_mlittle_endian)) {
420 llvm::Triple LE = Target.getLittleEndianArchVariant();
421 if (LE.getArch() != llvm::Triple::UnknownArch)
422 Target = std::move(LE);
423 } else {
424 llvm::Triple BE = Target.getBigEndianArchVariant();
425 if (BE.getArch() != llvm::Triple::UnknownArch)
426 Target = std::move(BE);
427 }
428 }
429
430 // Skip further flag support on OSes which don't support '-m32' or '-m64'.
Douglas Katzman15a63ed2015-08-12 18:36:12 +0000431 if (Target.getArch() == llvm::Triple::tce ||
432 Target.getOS() == llvm::Triple::Minix)
Artem Belevich959e0542015-07-10 19:47:55 +0000433 return Target;
434
435 // Handle pseudo-target flags '-m64', '-mx32', '-m32' and '-m16'.
Andrey Turetskiy6a8b91d2016-04-21 10:16:48 +0000436 Arg *A = Args.getLastArg(options::OPT_m64, options::OPT_mx32,
437 options::OPT_m32, options::OPT_m16);
438 if (A) {
Artem Belevich959e0542015-07-10 19:47:55 +0000439 llvm::Triple::ArchType AT = llvm::Triple::UnknownArch;
440
441 if (A->getOption().matches(options::OPT_m64)) {
442 AT = Target.get64BitArchVariant().getArch();
443 if (Target.getEnvironment() == llvm::Triple::GNUX32)
444 Target.setEnvironment(llvm::Triple::GNU);
445 } else if (A->getOption().matches(options::OPT_mx32) &&
446 Target.get64BitArchVariant().getArch() == llvm::Triple::x86_64) {
447 AT = llvm::Triple::x86_64;
448 Target.setEnvironment(llvm::Triple::GNUX32);
449 } else if (A->getOption().matches(options::OPT_m32)) {
450 AT = Target.get32BitArchVariant().getArch();
451 if (Target.getEnvironment() == llvm::Triple::GNUX32)
452 Target.setEnvironment(llvm::Triple::GNU);
453 } else if (A->getOption().matches(options::OPT_m16) &&
454 Target.get32BitArchVariant().getArch() == llvm::Triple::x86) {
455 AT = llvm::Triple::x86;
456 Target.setEnvironment(llvm::Triple::CODE16);
457 }
458
459 if (AT != llvm::Triple::UnknownArch && AT != Target.getArch())
460 Target.setArch(AT);
461 }
462
Andrey Turetskiy6a8b91d2016-04-21 10:16:48 +0000463 // Handle -miamcu flag.
Andrey Turetskiy5fea71c2016-06-29 10:57:17 +0000464 if (Args.hasFlag(options::OPT_miamcu, options::OPT_mno_iamcu, false)) {
465 if (Target.get32BitArchVariant().getArch() != llvm::Triple::x86)
466 D.Diag(diag::err_drv_unsupported_opt_for_target) << "-miamcu"
467 << Target.str();
Andrey Turetskiy6a8b91d2016-04-21 10:16:48 +0000468
Andrey Turetskiy5fea71c2016-06-29 10:57:17 +0000469 if (A && !A->getOption().matches(options::OPT_m32))
470 D.Diag(diag::err_drv_argument_not_allowed_with)
471 << "-miamcu" << A->getBaseArg().getAsString(Args);
Andrey Turetskiy6a8b91d2016-04-21 10:16:48 +0000472
Andrey Turetskiy5fea71c2016-06-29 10:57:17 +0000473 Target.setArch(llvm::Triple::x86);
474 Target.setArchName("i586");
475 Target.setEnvironment(llvm::Triple::UnknownEnvironment);
476 Target.setEnvironmentName("");
477 Target.setOS(llvm::Triple::ELFIAMCU);
478 Target.setVendor(llvm::Triple::UnknownVendor);
479 Target.setVendorName("intel");
Andrey Turetskiy6a8b91d2016-04-21 10:16:48 +0000480 }
481
Artem Belevich959e0542015-07-10 19:47:55 +0000482 return Target;
483}
484
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000485// Parse the LTO options and record the type of LTO compilation
Teresa Johnson945bc502015-10-15 20:35:53 +0000486// based on which -f(no-)?lto(=.*)? option occurs last.
487void Driver::setLTOMode(const llvm::opt::ArgList &Args) {
488 LTOMode = LTOK_None;
489 if (!Args.hasFlag(options::OPT_flto, options::OPT_flto_EQ,
490 options::OPT_fno_lto, false))
491 return;
492
493 StringRef LTOName("full");
494
495 const Arg *A = Args.getLastArg(options::OPT_flto_EQ);
Teresa Johnson6ef80dc2015-11-02 18:03:12 +0000496 if (A)
497 LTOName = A->getValue();
Teresa Johnson945bc502015-10-15 20:35:53 +0000498
499 LTOMode = llvm::StringSwitch<LTOKind>(LTOName)
500 .Case("full", LTOK_Full)
501 .Case("thin", LTOK_Thin)
502 .Default(LTOK_Unknown);
503
504 if (LTOMode == LTOK_Unknown) {
505 assert(A);
506 Diag(diag::err_drv_unsupported_option_argument) << A->getOption().getName()
507 << A->getValue();
508 }
509}
510
Samuel Antao39f9da22016-10-27 16:38:05 +0000511/// Compute the desired OpenMP runtime from the flags provided.
512Driver::OpenMPRuntimeKind Driver::getOpenMPRuntime(const ArgList &Args) const {
513 StringRef RuntimeName(CLANG_DEFAULT_OPENMP_RUNTIME);
514
515 const Arg *A = Args.getLastArg(options::OPT_fopenmp_EQ);
516 if (A)
517 RuntimeName = A->getValue();
518
519 auto RT = llvm::StringSwitch<OpenMPRuntimeKind>(RuntimeName)
520 .Case("libomp", OMPRT_OMP)
521 .Case("libgomp", OMPRT_GOMP)
522 .Case("libiomp5", OMPRT_IOMP5)
523 .Default(OMPRT_Unknown);
524
525 if (RT == OMPRT_Unknown) {
526 if (A)
527 Diag(diag::err_drv_unsupported_option_argument)
528 << A->getOption().getName() << A->getValue();
529 else
530 // FIXME: We could use a nicer diagnostic here.
531 Diag(diag::err_drv_unsupported_opt) << "-fopenmp";
532 }
533
534 return RT;
535}
536
Samuel Antaoc1ffba52016-06-13 18:10:57 +0000537void Driver::CreateOffloadingDeviceToolChains(Compilation &C,
538 InputList &Inputs) {
539
540 //
Yaxun Liuf5a6b962018-05-11 19:21:39 +0000541 // CUDA/HIP
Samuel Antaoc1ffba52016-06-13 18:10:57 +0000542 //
Yaxun Liuf5a6b962018-05-11 19:21:39 +0000543 // We need to generate a CUDA toolchain if any of the inputs has a CUDA
544 // or HIP type. However, mixed CUDA/HIP compilation is not supported.
545 bool IsCuda =
546 llvm::any_of(Inputs, [](std::pair<types::ID, const llvm::opt::Arg *> &I) {
Samuel Antaoc1ffba52016-06-13 18:10:57 +0000547 return types::isCuda(I.first);
Yaxun Liuf5a6b962018-05-11 19:21:39 +0000548 });
549 bool IsHIP =
550 llvm::any_of(Inputs,
551 [](std::pair<types::ID, const llvm::opt::Arg *> &I) {
552 return types::isHIP(I.first);
553 }) ||
554 C.getInputArgs().hasArg(options::OPT_hip_link);
555 if (IsCuda && IsHIP) {
556 Diag(clang::diag::err_drv_mix_cuda_hip);
557 return;
558 }
559 if (IsCuda || IsHIP) {
Justin Lebar66c4fd72016-11-18 00:41:22 +0000560 const ToolChain *HostTC = C.getSingleOffloadToolChain<Action::OFK_Host>();
561 const llvm::Triple &HostTriple = HostTC->getTriple();
Yaxun Liuf5a6b962018-05-11 19:21:39 +0000562 StringRef DeviceTripleStr;
563 auto OFK = IsHIP ? Action::OFK_HIP : Action::OFK_Cuda;
564 if (IsHIP) {
565 // HIP is only supported on amdgcn.
566 DeviceTripleStr = "amdgcn-amd-amdhsa";
567 } else {
568 // CUDA is only supported on nvptx.
569 DeviceTripleStr = HostTriple.isArch64Bit() ? "nvptx64-nvidia-cuda"
570 : "nvptx-nvidia-cuda";
571 }
572 llvm::Triple CudaTriple(DeviceTripleStr);
573 // Use the CUDA/HIP and host triples as the key into the ToolChains map,
574 // because the device toolchain we create depends on both.
David Blaikie6ad71012017-01-13 18:53:43 +0000575 auto &CudaTC = ToolChains[CudaTriple.str() + "/" + HostTriple.str()];
Justin Lebar66c4fd72016-11-18 00:41:22 +0000576 if (!CudaTC) {
David Blaikie6ad71012017-01-13 18:53:43 +0000577 CudaTC = llvm::make_unique<toolchains::CudaToolChain>(
Yaxun Liuf5a6b962018-05-11 19:21:39 +0000578 *this, CudaTriple, *HostTC, C.getInputArgs(), OFK);
Justin Lebar66c4fd72016-11-18 00:41:22 +0000579 }
Yaxun Liuf5a6b962018-05-11 19:21:39 +0000580 C.addOffloadDeviceToolChain(CudaTC.get(), OFK);
Samuel Antaoc1ffba52016-06-13 18:10:57 +0000581 }
582
583 //
Samuel Antao39f9da22016-10-27 16:38:05 +0000584 // OpenMP
585 //
586 // We need to generate an OpenMP toolchain if the user specified targets with
587 // the -fopenmp-targets option.
588 if (Arg *OpenMPTargets =
589 C.getInputArgs().getLastArg(options::OPT_fopenmp_targets_EQ)) {
590 if (OpenMPTargets->getNumValues()) {
591 // We expect that -fopenmp-targets is always used in conjunction with the
592 // option -fopenmp specifying a valid runtime with offloading support,
593 // i.e. libomp or libiomp.
594 bool HasValidOpenMPRuntime = C.getInputArgs().hasFlag(
595 options::OPT_fopenmp, options::OPT_fopenmp_EQ,
596 options::OPT_fno_openmp, false);
597 if (HasValidOpenMPRuntime) {
598 OpenMPRuntimeKind OpenMPKind = getOpenMPRuntime(C.getInputArgs());
599 HasValidOpenMPRuntime =
600 OpenMPKind == OMPRT_OMP || OpenMPKind == OMPRT_IOMP5;
601 }
602
603 if (HasValidOpenMPRuntime) {
604 llvm::StringMap<const char *> FoundNormalizedTriples;
605 for (const char *Val : OpenMPTargets->getValues()) {
606 llvm::Triple TT(Val);
607 std::string NormalizedName = TT.normalize();
608
609 // Make sure we don't have a duplicate triple.
610 auto Duplicate = FoundNormalizedTriples.find(NormalizedName);
611 if (Duplicate != FoundNormalizedTriples.end()) {
612 Diag(clang::diag::warn_drv_omp_offload_target_duplicate)
613 << Val << Duplicate->second;
614 continue;
615 }
616
617 // Store the current triple so that we can check for duplicates in the
618 // following iterations.
619 FoundNormalizedTriples[NormalizedName] = Val;
620
621 // If the specified target is invalid, emit a diagnostic.
622 if (TT.getArch() == llvm::Triple::UnknownArch)
623 Diag(clang::diag::err_drv_invalid_omp_target) << Val;
624 else {
Gheorghe-Teodor Bercea6a5df722017-07-06 16:08:15 +0000625 const ToolChain *TC;
626 // CUDA toolchains have to be selected differently. They pair host
627 // and device in their implementation.
628 if (TT.isNVPTX()) {
629 const ToolChain *HostTC =
630 C.getSingleOffloadToolChain<Action::OFK_Host>();
631 assert(HostTC && "Host toolchain should be always defined.");
632 auto &CudaTC =
Gheorghe-Teodor Bercea52898432017-08-09 01:02:19 +0000633 ToolChains[TT.str() + "/" + HostTC->getTriple().normalize()];
Gheorghe-Teodor Bercea6a5df722017-07-06 16:08:15 +0000634 if (!CudaTC)
635 CudaTC = llvm::make_unique<toolchains::CudaToolChain>(
Gheorghe-Teodor Bercea2c926932017-08-08 14:33:05 +0000636 *this, TT, *HostTC, C.getInputArgs(), Action::OFK_OpenMP);
Gheorghe-Teodor Bercea6a5df722017-07-06 16:08:15 +0000637 TC = CudaTC.get();
638 } else
639 TC = &getToolChain(C.getInputArgs(), TT);
640 C.addOffloadDeviceToolChain(TC, Action::OFK_OpenMP);
Samuel Antao39f9da22016-10-27 16:38:05 +0000641 }
642 }
643 } else
644 Diag(clang::diag::err_drv_expecting_fopenmp_with_fopenmp_targets);
645 } else
646 Diag(clang::diag::warn_drv_empty_joined_argument)
647 << OpenMPTargets->getAsString(C.getInputArgs());
648 }
649
650 //
Samuel Antaoc1ffba52016-06-13 18:10:57 +0000651 // TODO: Add support for other offloading programming models here.
652 //
Samuel Antaoc1ffba52016-06-13 18:10:57 +0000653}
654
Serge Pavlov208ac652018-01-01 13:27:01 +0000655/// Looks the given directories for the specified file.
656///
657/// \param[out] FilePath File path, if the file was found.
658/// \param[in] Dirs Directories used for the search.
659/// \param[in] FileName Name of the file to search for.
660/// \return True if file was found.
661///
662/// Looks for file specified by FileName sequentially in directories specified
663/// by Dirs.
664///
665static bool searchForFile(SmallVectorImpl<char> &FilePath,
666 ArrayRef<std::string> Dirs,
667 StringRef FileName) {
668 SmallString<128> WPath;
669 for (const StringRef &Dir : Dirs) {
670 if (Dir.empty())
671 continue;
672 WPath.clear();
673 llvm::sys::path::append(WPath, Dir, FileName);
674 llvm::sys::path::native(WPath);
675 if (llvm::sys::fs::is_regular_file(WPath)) {
676 FilePath = std::move(WPath);
677 return true;
678 }
679 }
680 return false;
681}
682
683bool Driver::readConfigFile(StringRef FileName) {
684 // Try reading the given file.
685 SmallVector<const char *, 32> NewCfgArgs;
686 if (!llvm::cl::readConfigFile(FileName, Saver, NewCfgArgs)) {
687 Diag(diag::err_drv_cannot_read_config_file) << FileName;
688 return true;
689 }
690
691 // Read options from config file.
692 llvm::SmallString<128> CfgFileName(FileName);
693 llvm::sys::path::native(CfgFileName);
694 ConfigFile = CfgFileName.str();
695 bool ContainErrors;
696 CfgOptions = llvm::make_unique<InputArgList>(
697 ParseArgStrings(NewCfgArgs, ContainErrors));
698 if (ContainErrors) {
699 CfgOptions.reset();
700 return true;
701 }
702
703 if (CfgOptions->hasArg(options::OPT_config)) {
704 CfgOptions.reset();
705 Diag(diag::err_drv_nested_config_file);
706 return true;
707 }
708
709 // Claim all arguments that come from a configuration file so that the driver
710 // does not warn on any that is unused.
711 for (Arg *A : *CfgOptions)
712 A->claim();
713 return false;
714}
715
716bool Driver::loadConfigFile() {
717 std::string CfgFileName;
718 bool FileSpecifiedExplicitly = false;
719
720 // Process options that change search path for config files.
721 if (CLOptions) {
722 if (CLOptions->hasArg(options::OPT_config_system_dir_EQ)) {
723 SmallString<128> CfgDir;
724 CfgDir.append(
725 CLOptions->getLastArgValue(options::OPT_config_system_dir_EQ));
726 if (!CfgDir.empty()) {
Sam McCall296d8322018-01-02 09:35:10 +0000727 if (llvm::sys::fs::make_absolute(CfgDir).value() != 0)
Serge Pavlov208ac652018-01-01 13:27:01 +0000728 SystemConfigDir.clear();
729 else
730 SystemConfigDir = std::string(CfgDir.begin(), CfgDir.end());
731 }
732 }
733 if (CLOptions->hasArg(options::OPT_config_user_dir_EQ)) {
734 SmallString<128> CfgDir;
735 CfgDir.append(
736 CLOptions->getLastArgValue(options::OPT_config_user_dir_EQ));
737 if (!CfgDir.empty()) {
Sam McCall296d8322018-01-02 09:35:10 +0000738 if (llvm::sys::fs::make_absolute(CfgDir).value() != 0)
Serge Pavlov208ac652018-01-01 13:27:01 +0000739 UserConfigDir.clear();
740 else
741 UserConfigDir = std::string(CfgDir.begin(), CfgDir.end());
742 }
743 }
744 }
745
746 // First try to find config file specified in command line.
747 if (CLOptions) {
748 std::vector<std::string> ConfigFiles =
749 CLOptions->getAllArgValues(options::OPT_config);
750 if (ConfigFiles.size() > 1) {
751 Diag(diag::err_drv_duplicate_config);
752 return true;
753 }
754
755 if (!ConfigFiles.empty()) {
756 CfgFileName = ConfigFiles.front();
757 assert(!CfgFileName.empty());
758
759 // If argument contains directory separator, treat it as a path to
760 // configuration file.
761 if (llvm::sys::path::has_parent_path(CfgFileName)) {
762 SmallString<128> CfgFilePath;
763 if (llvm::sys::path::is_relative(CfgFileName))
764 llvm::sys::fs::current_path(CfgFilePath);
765 llvm::sys::path::append(CfgFilePath, CfgFileName);
766 if (!llvm::sys::fs::is_regular_file(CfgFilePath)) {
767 Diag(diag::err_drv_config_file_not_exist) << CfgFilePath;
768 return true;
769 }
770 return readConfigFile(CfgFilePath);
771 }
772
773 FileSpecifiedExplicitly = true;
774 }
775 }
776
777 // If config file is not specified explicitly, try to deduce configuration
778 // from executable name. For instance, an executable 'armv7l-clang' will
779 // search for config file 'armv7l-clang.cfg'.
780 if (CfgFileName.empty() && !ClangNameParts.TargetPrefix.empty())
781 CfgFileName = ClangNameParts.TargetPrefix + '-' + ClangNameParts.ModeSuffix;
782
783 if (CfgFileName.empty())
784 return false;
785
786 // Determine architecture part of the file name, if it is present.
787 StringRef CfgFileArch = CfgFileName;
788 size_t ArchPrefixLen = CfgFileArch.find('-');
789 if (ArchPrefixLen == StringRef::npos)
790 ArchPrefixLen = CfgFileArch.size();
791 llvm::Triple CfgTriple;
792 CfgFileArch = CfgFileArch.take_front(ArchPrefixLen);
793 CfgTriple = llvm::Triple(llvm::Triple::normalize(CfgFileArch));
794 if (CfgTriple.getArch() == llvm::Triple::ArchType::UnknownArch)
795 ArchPrefixLen = 0;
796
797 if (!StringRef(CfgFileName).endswith(".cfg"))
798 CfgFileName += ".cfg";
799
800 // If config file starts with architecture name and command line options
801 // redefine architecture (with options like -m32 -LE etc), try finding new
802 // config file with that architecture.
803 SmallString<128> FixedConfigFile;
804 size_t FixedArchPrefixLen = 0;
805 if (ArchPrefixLen) {
806 // Get architecture name from config file name like 'i386.cfg' or
807 // 'armv7l-clang.cfg'.
808 // Check if command line options changes effective triple.
809 llvm::Triple EffectiveTriple = computeTargetTriple(*this,
810 CfgTriple.getTriple(), *CLOptions);
811 if (CfgTriple.getArch() != EffectiveTriple.getArch()) {
812 FixedConfigFile = EffectiveTriple.getArchName();
813 FixedArchPrefixLen = FixedConfigFile.size();
814 // Append the rest of original file name so that file name transforms
815 // like: i386-clang.cfg -> x86_64-clang.cfg.
816 if (ArchPrefixLen < CfgFileName.size())
817 FixedConfigFile += CfgFileName.substr(ArchPrefixLen);
818 }
819 }
820
821 // Prepare list of directories where config file is searched for.
822 SmallVector<std::string, 3> CfgFileSearchDirs;
823 CfgFileSearchDirs.push_back(UserConfigDir);
824 CfgFileSearchDirs.push_back(SystemConfigDir);
825 CfgFileSearchDirs.push_back(Dir);
826
827 // Try to find config file. First try file with corrected architecture.
828 llvm::SmallString<128> CfgFilePath;
829 if (!FixedConfigFile.empty()) {
830 if (searchForFile(CfgFilePath, CfgFileSearchDirs, FixedConfigFile))
831 return readConfigFile(CfgFilePath);
832 // If 'x86_64-clang.cfg' was not found, try 'x86_64.cfg'.
833 FixedConfigFile.resize(FixedArchPrefixLen);
834 FixedConfigFile.append(".cfg");
835 if (searchForFile(CfgFilePath, CfgFileSearchDirs, FixedConfigFile))
836 return readConfigFile(CfgFilePath);
837 }
838
839 // Then try original file name.
840 if (searchForFile(CfgFilePath, CfgFileSearchDirs, CfgFileName))
841 return readConfigFile(CfgFilePath);
842
843 // Finally try removing driver mode part: 'x86_64-clang.cfg' -> 'x86_64.cfg'.
844 if (!ClangNameParts.ModeSuffix.empty() &&
845 !ClangNameParts.TargetPrefix.empty()) {
846 CfgFileName.assign(ClangNameParts.TargetPrefix);
847 CfgFileName.append(".cfg");
848 if (searchForFile(CfgFilePath, CfgFileSearchDirs, CfgFileName))
849 return readConfigFile(CfgFilePath);
850 }
851
852 // Report error but only if config file was specified explicitly, by option
853 // --config. If it was deduced from executable name, it is not an error.
854 if (FileSpecifiedExplicitly) {
855 Diag(diag::err_drv_config_file_not_found) << CfgFileName;
856 for (const std::string &SearchDir : CfgFileSearchDirs)
857 if (!SearchDir.empty())
858 Diag(diag::note_drv_config_file_searched_in) << SearchDir;
859 return true;
860 }
861
862 return false;
863}
864
Chris Lattner54b16772011-07-23 17:14:25 +0000865Compilation *Driver::BuildCompilation(ArrayRef<const char *> ArgList) {
Daniel Dunbar2608c542009-03-18 01:38:48 +0000866 llvm::PrettyStackTraceString CrashInfo("Compilation construction");
867
Eric Christopherf901e852011-08-17 22:59:59 +0000868 // FIXME: Handle environment options which affect driver behavior, somewhere
Bill Wendlingadbeb9f2012-03-12 21:24:57 +0000869 // (client?). GCC_EXEC_PREFIX, LPATH, CC_PRINT_OPTIONS.
Chad Rosier82301162011-09-14 00:47:55 +0000870
David Majnemer85c25b42016-07-24 17:44:03 +0000871 if (Optional<std::string> CompilerPathValue =
872 llvm::sys::Process::GetEnv("COMPILER_PATH")) {
873 StringRef CompilerPath = *CompilerPathValue;
Chad Rosier82301162011-09-14 00:47:55 +0000874 while (!CompilerPath.empty()) {
Douglas Katzmana67e50c2015-06-26 15:47:46 +0000875 std::pair<StringRef, StringRef> Split =
876 CompilerPath.split(llvm::sys::EnvPathSeparator);
Chad Rosier82301162011-09-14 00:47:55 +0000877 PrefixDirs.push_back(Split.first);
878 CompilerPath = Split.second;
879 }
880 }
Daniel Dunbar5e0f6af2009-03-13 00:51:18 +0000881
Hans Wennborg70850d82013-07-18 20:29:38 +0000882 // We look for the driver mode option early, because the mode can affect
883 // how other options are parsed.
Zachary Turneraff19c32016-08-12 17:47:52 +0000884 ParseDriverMode(ClangExecutable, ArgList.slice(1));
Hans Wennborg70850d82013-07-18 20:29:38 +0000885
Daniel Dunbar5e0f6af2009-03-13 00:51:18 +0000886 // FIXME: What are we going to do with -V and -b?
887
Serge Pavlov208ac652018-01-01 13:27:01 +0000888 // Arguments specified in command line.
889 bool ContainsError;
890 CLOptions = llvm::make_unique<InputArgList>(
891 ParseArgStrings(ArgList.slice(1), ContainsError));
892
893 // Try parsing configuration file.
894 if (!ContainsError)
895 ContainsError = loadConfigFile();
896 bool HasConfigFile = !ContainsError && (CfgOptions.get() != nullptr);
897
898 // All arguments, from both config file and command line.
899 InputArgList Args = std::move(HasConfigFile ? std::move(*CfgOptions)
900 : std::move(*CLOptions));
901 if (HasConfigFile)
902 for (auto *Opt : *CLOptions) {
Serge Pavlovf015a562018-04-26 06:28:47 +0000903 if (Opt->getOption().matches(options::OPT_config))
904 continue;
905 unsigned Index = Args.MakeIndex(Opt->getSpelling());
Serge Pavlov208ac652018-01-01 13:27:01 +0000906 const Arg *BaseArg = &Opt->getBaseArg();
907 if (BaseArg == Opt)
908 BaseArg = nullptr;
909 Arg *Copy = new llvm::opt::Arg(Opt->getOption(), Opt->getSpelling(),
Serge Pavlovf015a562018-04-26 06:28:47 +0000910 Index, BaseArg);
Serge Pavlov208ac652018-01-01 13:27:01 +0000911 Copy->getValues() = Opt->getValues();
912 if (Opt->isClaimed())
913 Copy->claim();
914 Args.append(Copy);
915 }
916
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +0000917 // FIXME: This stuff needs to go into the Compilation, not the driver.
Douglas Katzmanb7e8ef02015-06-25 19:37:41 +0000918 bool CCCPrintPhases;
Daniel Dunbard02cb1d2009-03-05 06:38:47 +0000919
Filipe Cabecinhas136f35e2015-07-18 06:35:24 +0000920 // Silence driver warnings if requested
921 Diags.setIgnoreAllWarnings(Args.hasArg(options::OPT_w));
922
Rafael Espindola59ae7992009-12-07 18:28:29 +0000923 // -no-canonical-prefixes is used very early in main.
David Blaikie69a1d8c2015-06-22 22:07:27 +0000924 Args.ClaimAllArgs(options::OPT_no_canonical_prefixes);
Rafael Espindola59ae7992009-12-07 18:28:29 +0000925
Daniel Dunbar926f81f2010-08-02 02:38:03 +0000926 // Ignore -pipe.
David Blaikie69a1d8c2015-06-22 22:07:27 +0000927 Args.ClaimAllArgs(options::OPT_pipe);
Daniel Dunbar926f81f2010-08-02 02:38:03 +0000928
Daniel Dunbaracd69572009-12-04 21:55:23 +0000929 // Extract -ccc args.
Daniel Dunbaree66cf22009-03-10 20:52:46 +0000930 //
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +0000931 // FIXME: We need to figure out where this behavior should live. Most of it
932 // should be outside in the client; the parts that aren't should have proper
933 // options, either by introducing new ones or by overloading gcc ones like -V
934 // or -b.
Douglas Katzmanb7e8ef02015-06-25 19:37:41 +0000935 CCCPrintPhases = Args.hasArg(options::OPT_ccc_print_phases);
David Blaikie69a1d8c2015-06-22 22:07:27 +0000936 CCCPrintBindings = Args.hasArg(options::OPT_ccc_print_bindings);
937 if (const Arg *A = Args.getLastArg(options::OPT_ccc_gcc_name))
Richard Smithbd55daf2012-11-01 04:30:05 +0000938 CCCGenericGCCName = A->getValue();
David Blaikie69a1d8c2015-06-22 22:07:27 +0000939 CCCUsePCH =
940 Args.hasFlag(options::OPT_ccc_pch_is_pch, options::OPT_ccc_pch_is_pth);
Bruno Cardoso Lopes52dfe712017-04-12 21:46:20 +0000941 GenReproducer = Args.hasFlag(options::OPT_gen_reproducer,
942 options::OPT_fno_crash_diagnostics,
943 !!::getenv("FORCE_CLANG_DIAGNOSTICS_CRASH"));
Petr Hosekdd38d932018-05-29 22:35:39 +0000944 // FIXME: TargetTriple is used by the target-prefixed calls to as/ld
Joerg Sonnenberger17d75512012-02-22 19:15:16 +0000945 // and getToolChain is const.
Hans Wennborg2e274592013-08-13 23:38:57 +0000946 if (IsCLMode()) {
Hans Wennborg73609a02014-03-28 01:19:04 +0000947 // clang-cl targets MSVC-style Win32.
Petr Hosekdd38d932018-05-29 22:35:39 +0000948 llvm::Triple T(TargetTriple);
Hans Wennborg9d9ce7a2014-03-28 20:49:28 +0000949 T.setOS(llvm::Triple::Win32);
Hans Wennborg0f0e8d62015-09-18 17:11:50 +0000950 T.setVendor(llvm::Triple::PC);
Hans Wennborg9d9ce7a2014-03-28 20:49:28 +0000951 T.setEnvironment(llvm::Triple::MSVC);
Oleg Ranevskyy80523182017-08-31 20:31:30 +0000952 T.setObjectFormat(llvm::Triple::COFF);
Petr Hosekdd38d932018-05-29 22:35:39 +0000953 TargetTriple = T.str();
Hans Wennborg2e274592013-08-13 23:38:57 +0000954 }
David Blaikie69a1d8c2015-06-22 22:07:27 +0000955 if (const Arg *A = Args.getLastArg(options::OPT_target))
Petr Hosekdd38d932018-05-29 22:35:39 +0000956 TargetTriple = A->getValue();
David Blaikie69a1d8c2015-06-22 22:07:27 +0000957 if (const Arg *A = Args.getLastArg(options::OPT_ccc_install_dir))
Richard Smithbd55daf2012-11-01 04:30:05 +0000958 Dir = InstalledDir = A->getValue();
David Blaikie69a1d8c2015-06-22 22:07:27 +0000959 for (const Arg *A : Args.filtered(options::OPT_B)) {
Benjamin Kramer1a648d12011-02-08 20:31:42 +0000960 A->claim();
Richard Smithbd55daf2012-11-01 04:30:05 +0000961 PrefixDirs.push_back(A->getValue(0));
Benjamin Kramer1a648d12011-02-08 20:31:42 +0000962 }
David Blaikie69a1d8c2015-06-22 22:07:27 +0000963 if (const Arg *A = Args.getLastArg(options::OPT__sysroot_EQ))
Richard Smithbd55daf2012-11-01 04:30:05 +0000964 SysRoot = A->getValue();
David Blaikie69a1d8c2015-06-22 22:07:27 +0000965 if (const Arg *A = Args.getLastArg(options::OPT__dyld_prefix_EQ))
Peter Collingbourne9d9e1fc2013-05-27 21:40:20 +0000966 DyldPrefix = A->getValue();
Daniel Dunbaree66cf22009-03-10 20:52:46 +0000967
David Blaikie69a1d8c2015-06-22 22:07:27 +0000968 if (const Arg *A = Args.getLastArg(options::OPT_resource_dir))
Bob Wilsona20a1da2013-03-23 05:17:59 +0000969 ResourceDir = A->getValue();
Jim Grosbach061dabf2013-03-12 20:17:58 +0000970
David Blaikie69a1d8c2015-06-22 22:07:27 +0000971 if (const Arg *A = Args.getLastArg(options::OPT_save_temps_EQ)) {
Reid Kleckner68eb60b2015-02-02 22:41:48 +0000972 SaveTemps = llvm::StringSwitch<SaveTempsMode>(A->getValue())
973 .Case("cwd", SaveTempsCwd)
974 .Case("obj", SaveTempsObj)
975 .Default(SaveTempsCwd);
976 }
977
Steven Wu1257cd82016-05-18 17:04:52 +0000978 setLTOMode(Args);
979
Steven Wu844ab6a2016-11-16 06:06:44 +0000980 // Process -fembed-bitcode= flags.
981 if (Arg *A = Args.getLastArg(options::OPT_fembed_bitcode_EQ)) {
982 StringRef Name = A->getValue();
983 unsigned Model = llvm::StringSwitch<unsigned>(Name)
984 .Case("off", EmbedNone)
985 .Case("all", EmbedBitcode)
986 .Case("bitcode", EmbedBitcode)
987 .Case("marker", EmbedMarker)
988 .Default(~0U);
989 if (Model == ~0U) {
990 Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args)
991 << Name;
992 } else
993 BitcodeEmbed = static_cast<BitcodeEmbedMode>(Model);
Steven Wu574b0f22016-03-01 01:07:58 +0000994 }
995
David Blaikie69a1d8c2015-06-22 22:07:27 +0000996 std::unique_ptr<llvm::opt::InputArgList> UArgs =
997 llvm::make_unique<InputArgList>(std::move(Args));
998
Daniel Dunbar775d4062010-06-11 22:00:26 +0000999 // Perform the default argument translations.
David Blaikie69a1d8c2015-06-22 22:07:27 +00001000 DerivedArgList *TranslatedArgs = TranslateInputArgs(*UArgs);
Daniel Dunbar775d4062010-06-11 22:00:26 +00001001
Chandler Carruthcb916192012-01-25 08:49:21 +00001002 // Owned by the host.
Andrey Turetskiy6a8b91d2016-04-21 10:16:48 +00001003 const ToolChain &TC = getToolChain(
Petr Hosekdd38d932018-05-29 22:35:39 +00001004 *UArgs, computeTargetTriple(*this, TargetTriple, *UArgs));
Chandler Carruthcb916192012-01-25 08:49:21 +00001005
Daniel Dunbar3ce436d2009-03-16 06:42:30 +00001006 // The compilation takes ownership of Args.
Benjamin Kramer43c0f482017-06-30 13:21:27 +00001007 Compilation *C = new Compilation(*this, TC, UArgs.release(), TranslatedArgs,
1008 ContainsError);
Daniel Dunbarf0eddb82009-03-18 02:55:38 +00001009
Daniel Dunbarf0eddb82009-03-18 02:55:38 +00001010 if (!HandleImmediateArgs(*C))
1011 return C;
1012
Chad Rosierecdede82011-08-12 22:08:57 +00001013 // Construct the list of inputs.
1014 InputList Inputs;
Hans Wennborged1d0722013-08-13 21:32:29 +00001015 BuildInputs(C->getDefaultToolChain(), *TranslatedArgs, Inputs);
Chad Rosierecdede82011-08-12 22:08:57 +00001016
Samuel Antaoc1ffba52016-06-13 18:10:57 +00001017 // Populate the tool chains for the offloading devices, if any.
1018 CreateOffloadingDeviceToolChains(*C, Inputs);
Justin Lebar0e450a52016-03-30 23:30:25 +00001019
Chandler Carruth7f1417f2012-01-24 10:43:44 +00001020 // Construct the list of abstract actions to perform for this compilation. On
Tim Northover157d9112014-01-16 08:48:16 +00001021 // MachO targets this uses the driver-driver and universal actions.
1022 if (TC.getTriple().isOSBinFormatMachO())
Artem Belevich5e2a3ec2015-11-17 22:28:40 +00001023 BuildUniversalActions(*C, C->getDefaultToolChain(), Inputs);
Daniel Dunbarf0eddb82009-03-18 02:55:38 +00001024 else
Justin Lebar0f3474c2016-02-11 02:00:50 +00001025 BuildActions(*C, C->getArgs(), Inputs, C->getActions());
Daniel Dunbarf0eddb82009-03-18 02:55:38 +00001026
Douglas Katzmanb7e8ef02015-06-25 19:37:41 +00001027 if (CCCPrintPhases) {
Daniel Dunbareb843be2009-03-18 03:13:20 +00001028 PrintActions(*C);
Daniel Dunbarf0eddb82009-03-18 02:55:38 +00001029 return C;
1030 }
1031
1032 BuildJobs(*C);
Daniel Dunbaradc91e62009-03-15 01:38:15 +00001033
1034 return C;
Daniel Dunbaree66cf22009-03-10 20:52:46 +00001035}
1036
Justin Bognered9cbe02015-07-09 06:58:31 +00001037static void printArgList(raw_ostream &OS, const llvm::opt::ArgList &Args) {
1038 llvm::opt::ArgStringList ASL;
1039 for (const auto *A : Args)
1040 A->render(Args, ASL);
1041
1042 for (auto I = ASL.begin(), E = ASL.end(); I != E; ++I) {
1043 if (I != ASL.begin())
1044 OS << ' ';
1045 Command::printArg(OS, *I, true);
1046 }
1047 OS << '\n';
1048}
1049
Bruno Cardoso Lopes02681c42016-11-17 21:41:22 +00001050bool Driver::getCrashDiagnosticFile(StringRef ReproCrashFilename,
1051 SmallString<128> &CrashDiagDir) {
1052 using namespace llvm::sys;
1053 assert(llvm::Triple(llvm::sys::getProcessTriple()).isOSDarwin() &&
1054 "Only knows about .crash files on Darwin");
1055
1056 // The .crash file can be found on at ~/Library/Logs/DiagnosticReports/
1057 // (or /Library/Logs/DiagnosticReports for root) and has the filename pattern
1058 // clang-<VERSION>_<YYYY-MM-DD-HHMMSS>_<hostname>.crash.
1059 path::home_directory(CrashDiagDir);
1060 if (CrashDiagDir.startswith("/var/root"))
1061 CrashDiagDir = "/";
1062 path::append(CrashDiagDir, "Library/Logs/DiagnosticReports");
1063 int PID =
1064#if LLVM_ON_UNIX
1065 getpid();
1066#else
1067 0;
1068#endif
1069 std::error_code EC;
1070 fs::file_status FileStatus;
1071 TimePoint<> LastAccessTime;
1072 SmallString<128> CrashFilePath;
1073 // Lookup the .crash files and get the one generated by a subprocess spawned
1074 // by this driver invocation.
1075 for (fs::directory_iterator File(CrashDiagDir, EC), FileEnd;
1076 File != FileEnd && !EC; File.increment(EC)) {
1077 StringRef FileName = path::filename(File->path());
1078 if (!FileName.startswith(Name))
1079 continue;
1080 if (fs::status(File->path(), FileStatus))
1081 continue;
1082 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> CrashFile =
1083 llvm::MemoryBuffer::getFile(File->path());
1084 if (!CrashFile)
1085 continue;
1086 // The first line should start with "Process:", otherwise this isn't a real
1087 // .crash file.
1088 StringRef Data = CrashFile.get()->getBuffer();
1089 if (!Data.startswith("Process:"))
1090 continue;
1091 // Parse parent process pid line, e.g: "Parent Process: clang-4.0 [79141]"
1092 size_t ParentProcPos = Data.find("Parent Process:");
1093 if (ParentProcPos == StringRef::npos)
1094 continue;
1095 size_t LineEnd = Data.find_first_of("\n", ParentProcPos);
1096 if (LineEnd == StringRef::npos)
1097 continue;
1098 StringRef ParentProcess = Data.slice(ParentProcPos+15, LineEnd).trim();
1099 int OpenBracket = -1, CloseBracket = -1;
1100 for (size_t i = 0, e = ParentProcess.size(); i < e; ++i) {
1101 if (ParentProcess[i] == '[')
1102 OpenBracket = i;
1103 if (ParentProcess[i] == ']')
1104 CloseBracket = i;
1105 }
1106 // Extract the parent process PID from the .crash file and check whether
1107 // it matches this driver invocation pid.
1108 int CrashPID;
1109 if (OpenBracket < 0 || CloseBracket < 0 ||
1110 ParentProcess.slice(OpenBracket + 1, CloseBracket)
1111 .getAsInteger(10, CrashPID) || CrashPID != PID) {
1112 continue;
1113 }
1114
1115 // Found a .crash file matching the driver pid. To avoid getting an older
1116 // and misleading crash file, continue looking for the most recent.
1117 // FIXME: the driver can dispatch multiple cc1 invocations, leading to
1118 // multiple crashes poiting to the same parent process. Since the driver
1119 // does not collect pid information for the dispatched invocation there's
1120 // currently no way to distinguish among them.
1121 const auto FileAccessTime = FileStatus.getLastModificationTime();
1122 if (FileAccessTime > LastAccessTime) {
1123 CrashFilePath.assign(File->path());
1124 LastAccessTime = FileAccessTime;
1125 }
1126 }
1127
1128 // If found, copy it over to the location of other reproducer files.
1129 if (!CrashFilePath.empty()) {
1130 EC = fs::copy_file(CrashFilePath, ReproCrashFilename);
1131 if (EC)
1132 return false;
1133 return true;
1134 }
1135
1136 return false;
1137}
1138
Eric Christopherf901e852011-08-17 22:59:59 +00001139// When clang crashes, produce diagnostic information including the fully
1140// preprocessed source file(s). Request that the developer attach the
Chad Rosierbe10f982011-08-02 17:58:04 +00001141// diagnostic information to a bug report.
Alex Lorenz045c5142018-04-07 00:03:27 +00001142void Driver::generateCompilationDiagnostics(
1143 Compilation &C, const Command &FailingCommand,
1144 StringRef AdditionalInformation, CompilationDiagnosticReport *Report) {
Chad Rosier877c0a22012-02-22 00:30:39 +00001145 if (C.getArgs().hasArg(options::OPT_fno_crash_diagnostics))
Chad Rosier62135492012-07-09 17:31:28 +00001146 return;
Chad Rosierbee5a1d2012-03-07 00:30:40 +00001147
Chad Rosierdbf46a12013-02-01 18:30:26 +00001148 // Don't try to generate diagnostics for link or dsymutil jobs.
Justin Bognere1a33d12014-10-20 21:02:05 +00001149 if (FailingCommand.getCreator().isLinkJob() ||
1150 FailingCommand.getCreator().isDsymutilJob())
Chad Rosier877c0a22012-02-22 00:30:39 +00001151 return;
1152
Chad Rosier8179f112012-06-19 17:51:34 +00001153 // Print the version of the compiler.
1154 PrintVersion(C, llvm::errs());
1155
Chad Rosierbe10f982011-08-02 17:58:04 +00001156 Diag(clang::diag::note_drv_command_failed_diag_msg)
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001157 << "PLEASE submit a bug report to " BUG_REPORT_URL " and include the "
1158 "crash backtrace, preprocessed source, and associated run script.";
Chad Rosierbe10f982011-08-02 17:58:04 +00001159
1160 // Suppress driver output and emit preprocessor output to temp file.
Hans Wennborg70850d82013-07-18 20:29:38 +00001161 Mode = CPPMode;
Chad Rosierbe10f982011-08-02 17:58:04 +00001162 CCGenDiagnostics = true;
1163
Chad Rosiercdb008d2011-11-02 21:29:05 +00001164 // Save the original job command(s).
Justin Bogner25645152014-10-21 17:24:44 +00001165 Command Cmd = FailingCommand;
Chad Rosiercdb008d2011-11-02 21:29:05 +00001166
Richard Smith5bb4cdf2012-12-20 02:22:15 +00001167 // Keep track of whether we produce any errors while trying to produce
1168 // preprocessed sources.
1169 DiagnosticErrorTrap Trap(Diags);
1170
1171 // Suppress tool output.
Chad Rosierbe10f982011-08-02 17:58:04 +00001172 C.initCompilationForDiagnostics();
Chad Rosierecdede82011-08-12 22:08:57 +00001173
1174 // Construct the list of inputs.
1175 InputList Inputs;
1176 BuildInputs(C.getDefaultToolChain(), C.getArgs(), Inputs);
Chad Rosierbe10f982011-08-02 17:58:04 +00001177
Chad Rosier4f81fc22011-08-12 23:30:05 +00001178 for (InputList::iterator it = Inputs.begin(), ie = Inputs.end(); it != ie;) {
Chad Rosierd57133d2011-08-18 00:22:25 +00001179 bool IgnoreInput = false;
1180
1181 // Ignore input from stdin or any inputs that cannot be preprocessed.
Paul Robinsonf44157d2014-04-28 22:24:44 +00001182 // Check type first as not all linker inputs have a value.
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001183 if (types::getPreprocessedType(it->first) == types::TY_INVALID) {
Paul Robinsonf44157d2014-04-28 22:24:44 +00001184 IgnoreInput = true;
1185 } else if (!strcmp(it->second->getValue(), "-")) {
Chad Rosierd57133d2011-08-18 00:22:25 +00001186 Diag(clang::diag::note_drv_command_failed_diag_msg)
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001187 << "Error generating preprocessed source(s) - "
1188 "ignoring input from stdin.";
Chad Rosierd57133d2011-08-18 00:22:25 +00001189 IgnoreInput = true;
Chad Rosierd57133d2011-08-18 00:22:25 +00001190 }
1191
1192 if (IgnoreInput) {
Chad Rosier4f81fc22011-08-12 23:30:05 +00001193 it = Inputs.erase(it);
1194 ie = Inputs.end();
Chad Rosier6fdf38b2011-08-17 23:08:45 +00001195 } else {
Chad Rosier4f81fc22011-08-12 23:30:05 +00001196 ++it;
Chad Rosier6fdf38b2011-08-17 23:08:45 +00001197 }
Chad Rosier4f81fc22011-08-12 23:30:05 +00001198 }
Chad Rosierd57133d2011-08-18 00:22:25 +00001199
Chad Rosierc5103c32013-01-29 23:57:10 +00001200 if (Inputs.empty()) {
1201 Diag(clang::diag::note_drv_command_failed_diag_msg)
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001202 << "Error generating preprocessed source(s) - "
1203 "no preprocessable inputs.";
Chad Rosierc5103c32013-01-29 23:57:10 +00001204 return;
1205 }
1206
Chad Rosiere75ef402011-09-06 23:52:36 +00001207 // Don't attempt to generate preprocessed files if multiple -arch options are
Chad Rosier636d2832012-02-13 18:16:28 +00001208 // used, unless they're all duplicates.
1209 llvm::StringSet<> ArchNames;
Saleem Abdulrasool688b6bc2014-12-29 19:01:36 +00001210 for (const Arg *A : C.getArgs()) {
Chad Rosiere75ef402011-09-06 23:52:36 +00001211 if (A->getOption().matches(options::OPT_arch)) {
Richard Smithbd55daf2012-11-01 04:30:05 +00001212 StringRef ArchName = A->getValue();
Chad Rosier636d2832012-02-13 18:16:28 +00001213 ArchNames.insert(ArchName);
Chad Rosiere75ef402011-09-06 23:52:36 +00001214 }
1215 }
Chad Rosier636d2832012-02-13 18:16:28 +00001216 if (ArchNames.size() > 1) {
1217 Diag(clang::diag::note_drv_command_failed_diag_msg)
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001218 << "Error generating preprocessed source(s) - cannot generate "
1219 "preprocessed source with multiple -arch options.";
Chad Rosier636d2832012-02-13 18:16:28 +00001220 return;
1221 }
Chad Rosiere75ef402011-09-06 23:52:36 +00001222
Chandler Carruth7f1417f2012-01-24 10:43:44 +00001223 // Construct the list of abstract actions to perform for this compilation. On
1224 // Darwin OSes this uses the driver-driver and builds universal actions.
Chandler Carruthcb916192012-01-25 08:49:21 +00001225 const ToolChain &TC = C.getDefaultToolChain();
Tim Northover157d9112014-01-16 08:48:16 +00001226 if (TC.getTriple().isOSBinFormatMachO())
Artem Belevich5e2a3ec2015-11-17 22:28:40 +00001227 BuildUniversalActions(C, TC, Inputs);
Chad Rosierbe10f982011-08-02 17:58:04 +00001228 else
Justin Lebar0f3474c2016-02-11 02:00:50 +00001229 BuildActions(C, C.getArgs(), Inputs, C.getActions());
Chad Rosierbe10f982011-08-02 17:58:04 +00001230
1231 BuildJobs(C);
1232
1233 // If there were errors building the compilation, quit now.
Richard Smith5bb4cdf2012-12-20 02:22:15 +00001234 if (Trap.hasErrorOccurred()) {
Chad Rosierbe10f982011-08-02 17:58:04 +00001235 Diag(clang::diag::note_drv_command_failed_diag_msg)
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001236 << "Error generating preprocessed source(s).";
Chad Rosierbe10f982011-08-02 17:58:04 +00001237 return;
1238 }
1239
1240 // Generate preprocessed output.
Chad Rosierdd60e092013-01-29 20:15:05 +00001241 SmallVector<std::pair<int, const Command *>, 4> FailingCommands;
Justin Bogner0cd92482015-07-02 22:52:08 +00001242 C.ExecuteJobs(C.getJobs(), FailingCommands);
Chad Rosierbe10f982011-08-02 17:58:04 +00001243
Justin Bognerbc89b182014-10-20 21:20:27 +00001244 // If any of the preprocessing commands failed, clean up and exit.
1245 if (!FailingCommands.empty()) {
Reid Kleckner68eb60b2015-02-02 22:41:48 +00001246 if (!isSaveTempsEnabled())
Chad Rosierbe10f982011-08-02 17:58:04 +00001247 C.CleanupFileList(C.getTempFiles(), true);
1248
1249 Diag(clang::diag::note_drv_command_failed_diag_msg)
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001250 << "Error generating preprocessed source(s).";
Justin Bognerbc89b182014-10-20 21:20:27 +00001251 return;
Chad Rosierbe10f982011-08-02 17:58:04 +00001252 }
Justin Bognerbc89b182014-10-20 21:20:27 +00001253
Justin Bognerc1fdf7f2014-10-20 21:47:56 +00001254 const ArgStringList &TempFiles = C.getTempFiles();
1255 if (TempFiles.empty()) {
1256 Diag(clang::diag::note_drv_command_failed_diag_msg)
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001257 << "Error generating preprocessed source(s).";
Justin Bognerc1fdf7f2014-10-20 21:47:56 +00001258 return;
1259 }
1260
Justin Bognerbc89b182014-10-20 21:20:27 +00001261 Diag(clang::diag::note_drv_command_failed_diag_msg)
1262 << "\n********************\n\n"
1263 "PLEASE ATTACH THE FOLLOWING FILES TO THE BUG REPORT:\n"
1264 "Preprocessed source(s) and associated run script(s) are located at:";
Justin Bognerbc89b182014-10-20 21:20:27 +00001265
Justin Bogner659ecc32014-10-20 22:47:23 +00001266 SmallString<128> VFS;
Bruno Cardoso Lopes02681c42016-11-17 21:41:22 +00001267 SmallString<128> ReproCrashFilename;
Justin Bogner659ecc32014-10-20 22:47:23 +00001268 for (const char *TempFile : TempFiles) {
Justin Bognerc1fdf7f2014-10-20 21:47:56 +00001269 Diag(clang::diag::note_drv_command_failed_diag_msg) << TempFile;
Alex Lorenz045c5142018-04-07 00:03:27 +00001270 if (Report)
1271 Report->TemporaryFiles.push_back(TempFile);
Bruno Cardoso Lopes02681c42016-11-17 21:41:22 +00001272 if (ReproCrashFilename.empty()) {
1273 ReproCrashFilename = TempFile;
1274 llvm::sys::path::replace_extension(ReproCrashFilename, ".crash");
1275 }
Justin Bogner659ecc32014-10-20 22:47:23 +00001276 if (StringRef(TempFile).endswith(".cache")) {
1277 // In some cases (modules) we'll dump extra data to help with reproducing
1278 // the crash into a directory next to the output.
1279 VFS = llvm::sys::path::filename(TempFile);
1280 llvm::sys::path::append(VFS, "vfs", "vfs.yaml");
1281 }
1282 }
Justin Bognerc1fdf7f2014-10-20 21:47:56 +00001283
1284 // Assume associated files are based off of the first temporary file.
Justin Bogner25645152014-10-21 17:24:44 +00001285 CrashReportInfo CrashInfo(TempFiles[0], VFS);
Justin Bognerc1fdf7f2014-10-20 21:47:56 +00001286
Justin Bogner25645152014-10-21 17:24:44 +00001287 std::string Script = CrashInfo.Filename.rsplit('.').first.str() + ".sh";
Justin Bognerc1fdf7f2014-10-20 21:47:56 +00001288 std::error_code EC;
Justin Bognerc1fdf7f2014-10-20 21:47:56 +00001289 llvm::raw_fd_ostream ScriptOS(Script, EC, llvm::sys::fs::F_Excl);
1290 if (EC) {
1291 Diag(clang::diag::note_drv_command_failed_diag_msg)
1292 << "Error generating run script: " + Script + " " + EC.message();
1293 } else {
Justin Bogner42220ed2015-03-12 00:14:35 +00001294 ScriptOS << "# Crash reproducer for " << getClangFullVersion() << "\n"
Justin Bognered9cbe02015-07-09 06:58:31 +00001295 << "# Driver args: ";
1296 printArgList(ScriptOS, C.getInputArgs());
1297 ScriptOS << "# Original command: ";
Justin Bogner42220ed2015-03-12 00:14:35 +00001298 Cmd.Print(ScriptOS, "\n", /*Quote=*/true);
Justin Bogner33bdbc62014-10-21 18:03:08 +00001299 Cmd.Print(ScriptOS, "\n", /*Quote=*/true, &CrashInfo);
Alex Lorenz045c5142018-04-07 00:03:27 +00001300 if (!AdditionalInformation.empty())
1301 ScriptOS << "\n# Additional information: " << AdditionalInformation
1302 << "\n";
1303 if (Report)
1304 Report->TemporaryFiles.push_back(Script);
Justin Bognerc1fdf7f2014-10-20 21:47:56 +00001305 Diag(clang::diag::note_drv_command_failed_diag_msg) << Script;
Justin Bognerbc89b182014-10-20 21:20:27 +00001306 }
Saleem Abdulrasool3661a822015-01-12 02:33:09 +00001307
Bruno Cardoso Lopes02681c42016-11-17 21:41:22 +00001308 // On darwin, provide information about the .crash diagnostic report.
1309 if (llvm::Triple(llvm::sys::getProcessTriple()).isOSDarwin()) {
1310 SmallString<128> CrashDiagDir;
1311 if (getCrashDiagnosticFile(ReproCrashFilename, CrashDiagDir)) {
1312 Diag(clang::diag::note_drv_command_failed_diag_msg)
1313 << ReproCrashFilename.str();
1314 } else { // Suggest a directory for the user to look for .crash files.
1315 llvm::sys::path::append(CrashDiagDir, Name);
1316 CrashDiagDir += "_<YYYY-MM-DD-HHMMSS>_<hostname>.crash";
1317 Diag(clang::diag::note_drv_command_failed_diag_msg)
1318 << "Crash backtrace is located in";
1319 Diag(clang::diag::note_drv_command_failed_diag_msg)
1320 << CrashDiagDir.str();
1321 Diag(clang::diag::note_drv_command_failed_diag_msg)
1322 << "(choose the .crash file that corresponds to your crash)";
1323 }
1324 }
1325
Saleem Abdulrasool3661a822015-01-12 02:33:09 +00001326 for (const auto &A : C.getArgs().filtered(options::OPT_frewrite_map_file,
1327 options::OPT_frewrite_map_file_EQ))
1328 Diag(clang::diag::note_drv_command_failed_diag_msg) << A->getValue();
1329
Justin Bognerbc89b182014-10-20 21:20:27 +00001330 Diag(clang::diag::note_drv_command_failed_diag_msg)
1331 << "\n\n********************";
Chad Rosierbe10f982011-08-02 17:58:04 +00001332}
1333
Justin Bogner0cd92482015-07-02 22:52:08 +00001334void Driver::setUpResponseFiles(Compilation &C, Command &Cmd) {
Oleg Ranevskyycd516372016-01-05 19:54:39 +00001335 // Since commandLineFitsWithinSystemLimits() may underestimate system's capacity
Reid Kleckner0290c9c2014-09-15 17:45:39 +00001336 // if the tool does not support response files, there is a chance/ that things
1337 // will just work without a response file, so we silently just skip it.
Justin Bogner0cd92482015-07-02 22:52:08 +00001338 if (Cmd.getCreator().getResponseFilesSupport() == Tool::RF_None ||
Oleg Ranevskyycd516372016-01-05 19:54:39 +00001339 llvm::sys::commandLineFitsWithinSystemLimits(Cmd.getExecutable(), Cmd.getArguments()))
Reid Kleckner0290c9c2014-09-15 17:45:39 +00001340 return;
1341
1342 std::string TmpName = GetTemporaryPath("response", "txt");
Malcolm Parsonsf76f6502016-11-02 10:39:27 +00001343 Cmd.setResponseFile(C.addTempFile(C.getArgs().MakeArgString(TmpName)));
Reid Kleckner0290c9c2014-09-15 17:45:39 +00001344}
1345
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001346int Driver::ExecuteCompilation(
1347 Compilation &C,
1348 SmallVectorImpl<std::pair<int, const Command *>> &FailingCommands) {
Daniel Dunbar38bfda62009-07-01 20:03:04 +00001349 // Just print if -### was present.
1350 if (C.getArgs().hasArg(options::OPT__HASH_HASH_HASH)) {
Hans Wennborgb212b342013-09-12 18:23:34 +00001351 C.getJobs().Print(llvm::errs(), "\n", true);
Daniel Dunbar38bfda62009-07-01 20:03:04 +00001352 return 0;
1353 }
1354
1355 // If there were errors building the compilation, quit now.
Chad Rosierbe10f982011-08-02 17:58:04 +00001356 if (Diags.hasErrorOccurred())
Daniel Dunbar38bfda62009-07-01 20:03:04 +00001357 return 1;
1358
Reid Kleckner0290c9c2014-09-15 17:45:39 +00001359 // Set up response file names for each command, if necessary
Justin Bogner0cd92482015-07-02 22:52:08 +00001360 for (auto &Job : C.getJobs())
1361 setUpResponseFiles(C, Job);
Reid Kleckner0290c9c2014-09-15 17:45:39 +00001362
Justin Bogner0cd92482015-07-02 22:52:08 +00001363 C.ExecuteJobs(C.getJobs(), FailingCommands);
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001364
Daniel Dunbar38bfda62009-07-01 20:03:04 +00001365 // Remove temp files.
1366 C.CleanupFileList(C.getTempFiles());
1367
Daniel Dunbar07494792010-05-22 00:37:20 +00001368 // If the command succeeded, we are done.
Chad Rosierdd60e092013-01-29 20:15:05 +00001369 if (FailingCommands.empty())
1370 return 0;
Daniel Dunbar07494792010-05-22 00:37:20 +00001371
Chad Rosierdd60e092013-01-29 20:15:05 +00001372 // Otherwise, remove result files and print extra information about abnormal
1373 // failures.
Douglas Katzman6bbffc42015-06-25 18:51:37 +00001374 for (const auto &CmdPair : FailingCommands) {
1375 int Res = CmdPair.first;
1376 const Command *FailingCommand = CmdPair.second;
Daniel Dunbar38bfda62009-07-01 20:03:04 +00001377
Chad Rosierdd60e092013-01-29 20:15:05 +00001378 // Remove result files if we're not saving temps.
Reid Kleckner68eb60b2015-02-02 22:41:48 +00001379 if (!isSaveTempsEnabled()) {
Chad Rosierdd60e092013-01-29 20:15:05 +00001380 const JobAction *JA = cast<JobAction>(&FailingCommand->getSource());
1381 C.CleanupFileMap(C.getResultFiles(), JA, true);
1382
1383 // Failure result files are valid unless we crashed.
1384 if (Res < 0)
1385 C.CleanupFileMap(C.getFailureResultFiles(), JA, true);
1386 }
1387
1388 // Print extra information about abnormal failures, if possible.
1389 //
1390 // This is ad-hoc, but we don't want to be excessively noisy. If the result
Justin Bogner5aaf2e72014-06-26 20:59:36 +00001391 // status was 1, assume the command failed normally. In particular, if it
Chad Rosierdd60e092013-01-29 20:15:05 +00001392 // was the compiler then assume it gave a reasonable error code. Failures
1393 // in other tools are less common, and they generally have worse
1394 // diagnostics, so always print the diagnostic there.
1395 const Tool &FailingTool = FailingCommand->getCreator();
1396
1397 if (!FailingCommand->getCreator().hasGoodDiagnostics() || Res != 1) {
1398 // FIXME: See FIXME above regarding result code interpretation.
1399 if (Res < 0)
1400 Diag(clang::diag::err_drv_command_signalled)
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001401 << FailingTool.getShortName();
Chad Rosierdd60e092013-01-29 20:15:05 +00001402 else
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001403 Diag(clang::diag::err_drv_command_failed) << FailingTool.getShortName()
1404 << Res;
Chad Rosierdd60e092013-01-29 20:15:05 +00001405 }
Peter Collingbourne119cfaa2011-11-21 00:01:05 +00001406 }
Chad Rosierdd60e092013-01-29 20:15:05 +00001407 return 0;
Daniel Dunbar38bfda62009-07-01 20:03:04 +00001408}
1409
Daniel Dunbara7b5e212009-04-15 16:34:29 +00001410void Driver::PrintHelp(bool ShowHidden) const {
Hans Wennborg6ddc6902013-07-27 00:23:45 +00001411 unsigned IncludedFlagsBitmask;
1412 unsigned ExcludedFlagsBitmask;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00001413 std::tie(IncludedFlagsBitmask, ExcludedFlagsBitmask) =
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001414 getIncludeExcludeOptionFlagMasks();
Hans Wennborg6ddc6902013-07-27 00:23:45 +00001415
1416 ExcludedFlagsBitmask |= options::NoDriverOption;
1417 if (!ShowHidden)
1418 ExcludedFlagsBitmask |= HelpHidden;
1419
1420 getOpts().PrintHelp(llvm::outs(), Name.c_str(), DriverTitle.c_str(),
George Rimar5dbfa4e2017-07-26 09:10:17 +00001421 IncludedFlagsBitmask, ExcludedFlagsBitmask,
1422 /*ShowAllAliases=*/false);
Daniel Dunbar7c925282009-03-31 21:38:17 +00001423}
1424
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001425void Driver::PrintVersion(const Compilation &C, raw_ostream &OS) const {
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001426 // FIXME: The following handlers should use a callback mechanism, we don't
1427 // know what the client would like to do.
Ted Kremenek4c0df3d2010-01-23 02:11:34 +00001428 OS << getClangFullVersion() << '\n';
Daniel Dunbarb10248802009-03-26 16:09:13 +00001429 const ToolChain &TC = C.getDefaultToolChain();
Daniel Dunbar08e41d62009-07-21 20:06:58 +00001430 OS << "Target: " << TC.getTripleString() << '\n';
Daniel Dunbar10978e42009-06-16 23:32:58 +00001431
1432 // Print the threading model.
Jonathan Roelofsb140a102014-10-03 21:57:44 +00001433 if (Arg *A = C.getArgs().getLastArg(options::OPT_mthread_model)) {
1434 // Don't print if the ToolChain would have barfed on it already
1435 if (TC.isThreadModelSupported(A->getValue()))
1436 OS << "Thread model: " << A->getValue();
1437 } else
1438 OS << "Thread model: " << TC.getThreadModel();
1439 OS << '\n';
Chandler Carruth9ade6a92015-08-05 17:07:33 +00001440
1441 // Print out the install directory.
1442 OS << "InstalledDir: " << InstalledDir << '\n';
Serge Pavlov208ac652018-01-01 13:27:01 +00001443
1444 // If configuration file was used, print its path.
1445 if (!ConfigFile.empty())
1446 OS << "Configuration file: " << ConfigFile << '\n';
Daniel Dunbar5e0f6af2009-03-13 00:51:18 +00001447}
1448
Chris Lattner86ed5b02010-05-05 05:53:24 +00001449/// PrintDiagnosticCategories - Implement the --print-diagnostic-categories
1450/// option.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001451static void PrintDiagnosticCategories(raw_ostream &OS) {
Argyrios Kyrtzidis0e37afa2011-05-25 05:05:01 +00001452 // Skip the empty category.
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001453 for (unsigned i = 1, max = DiagnosticIDs::getNumberOfCategories(); i != max;
1454 ++i)
Argyrios Kyrtzidis0e37afa2011-05-25 05:05:01 +00001455 OS << i << ',' << DiagnosticIDs::getCategoryNameFromID(i) << '\n';
Chris Lattner86ed5b02010-05-05 05:53:24 +00001456}
1457
Yuka Takahashi41789e42018-03-05 08:54:20 +00001458void Driver::HandleAutocompletions(StringRef PassedFlags) const {
Yuka Takahashi503da8f2018-03-05 09:01:31 +00001459 if (PassedFlags == "")
1460 return;
Yuka Takahashi1a895202017-08-29 17:46:46 +00001461 // Print out all options that start with a given argument. This is used for
1462 // shell autocompletion.
1463 std::vector<std::string> SuggestedCompletions;
Yuka Takahashi41789e42018-03-05 08:54:20 +00001464 std::vector<std::string> Flags;
Yuka Takahashi1a895202017-08-29 17:46:46 +00001465
1466 unsigned short DisableFlags =
1467 options::NoDriverOption | options::Unsupported | options::Ignored;
Yuka Takahashi41789e42018-03-05 08:54:20 +00001468
1469 // Parse PassedFlags by "," as all the command-line flags are passed to this
1470 // function separated by ","
1471 StringRef TargetFlags = PassedFlags;
1472 while (TargetFlags != "") {
1473 StringRef CurFlag;
1474 std::tie(CurFlag, TargetFlags) = TargetFlags.split(",");
1475 Flags.push_back(std::string(CurFlag));
Yuka Takahashi1a895202017-08-29 17:46:46 +00001476 }
1477
Yuka Takahashi41789e42018-03-05 08:54:20 +00001478 // We want to show cc1-only options only when clang is invoked with -cc1 or
1479 // -Xclang.
Yuka Takahashi503da8f2018-03-05 09:01:31 +00001480 if (std::find(Flags.begin(), Flags.end(), "-Xclang") != Flags.end() ||
1481 std::find(Flags.begin(), Flags.end(), "-cc1") != Flags.end())
Yuka Takahashi41789e42018-03-05 08:54:20 +00001482 DisableFlags &= ~options::NoDriverOption;
1483
1484 StringRef Cur;
1485 Cur = Flags.at(Flags.size() - 1);
1486 StringRef Prev;
1487 if (Flags.size() >= 2) {
1488 Prev = Flags.at(Flags.size() - 2);
1489 SuggestedCompletions = Opts->suggestValueCompletions(Prev, Cur);
1490 }
1491
1492 if (SuggestedCompletions.empty())
1493 SuggestedCompletions = Opts->suggestValueCompletions(Cur, "");
1494
1495 if (SuggestedCompletions.empty()) {
Yuka Takahashi1a895202017-08-29 17:46:46 +00001496 // If the flag is in the form of "--autocomplete=-foo",
1497 // we were requested to print out all option names that start with "-foo".
1498 // For example, "--autocomplete=-fsyn" is expanded to "-fsyntax-only".
Yuka Takahashi41789e42018-03-05 08:54:20 +00001499 SuggestedCompletions = Opts->findByPrefix(Cur, DisableFlags);
Yuka Takahashi1a895202017-08-29 17:46:46 +00001500
1501 // We have to query the -W flags manually as they're not in the OptTable.
1502 // TODO: Find a good way to add them to OptTable instead and them remove
1503 // this code.
1504 for (StringRef S : DiagnosticIDs::getDiagnosticFlags())
Yuka Takahashi41789e42018-03-05 08:54:20 +00001505 if (S.startswith(Cur))
Yuka Takahashi1a895202017-08-29 17:46:46 +00001506 SuggestedCompletions.push_back(S);
Yuka Takahashi1a895202017-08-29 17:46:46 +00001507 }
1508
1509 // Sort the autocomplete candidates so that shells print them out in a
1510 // deterministic order. We could sort in any way, but we chose
1511 // case-insensitive sorting for consistency with the -help option
1512 // which prints out options in the case-insensitive alphabetical order.
Mandeep Singh Grangc205d8c2018-03-27 16:50:00 +00001513 llvm::sort(SuggestedCompletions.begin(), SuggestedCompletions.end(),
1514 [](StringRef A, StringRef B) {
1515 if (int X = A.compare_lower(B))
1516 return X < 0;
1517 return A.compare(B) > 0;
Mandeep Singh Grang8f54ae12017-11-20 18:49:14 +00001518 });
Yuka Takahashi1a895202017-08-29 17:46:46 +00001519
1520 llvm::outs() << llvm::join(SuggestedCompletions, "\n") << '\n';
1521}
1522
Daniel Dunbarf0eddb82009-03-18 02:55:38 +00001523bool Driver::HandleImmediateArgs(const Compilation &C) {
Daniel Dunbar18974bd2010-06-11 22:00:19 +00001524 // The order these options are handled in gcc is all over the place, but we
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001525 // don't expect inconsistencies w.r.t. that to matter in practice.
Daniel Dunbar7c925282009-03-31 21:38:17 +00001526
Daniel Dunbar1b09e042010-09-17 02:47:28 +00001527 if (C.getArgs().hasArg(options::OPT_dumpmachine)) {
1528 llvm::outs() << C.getDefaultToolChain().getTripleString() << '\n';
1529 return false;
1530 }
1531
Daniel Dunbara9bbcfa2009-04-04 05:17:38 +00001532 if (C.getArgs().hasArg(options::OPT_dumpversion)) {
Daniel Dunbare26e5002011-01-12 00:43:47 +00001533 // Since -dumpversion is only implemented for pedantic GCC compatibility, we
1534 // return an answer which matches our definition of __VERSION__.
1535 //
1536 // If we want to return a more correct answer some day, then we should
1537 // introduce a non-pedantically GCC compatible mode to Clang in which we
1538 // provide sensible definitions for -dumpversion, __VERSION__, etc.
1539 llvm::outs() << "4.2.1\n";
Daniel Dunbara9bbcfa2009-04-04 05:17:38 +00001540 return false;
1541 }
Daniel Dunbarfb3d7472010-06-14 21:23:12 +00001542
Chris Lattner86ed5b02010-05-05 05:53:24 +00001543 if (C.getArgs().hasArg(options::OPT__print_diagnostic_categories)) {
1544 PrintDiagnosticCategories(llvm::outs());
1545 return false;
1546 }
Daniel Dunbara9bbcfa2009-04-04 05:17:38 +00001547
James Molloya3c85b82012-05-01 14:57:16 +00001548 if (C.getArgs().hasArg(options::OPT_help) ||
Daniel Dunbara7b5e212009-04-15 16:34:29 +00001549 C.getArgs().hasArg(options::OPT__help_hidden)) {
1550 PrintHelp(C.getArgs().hasArg(options::OPT__help_hidden));
Daniel Dunbar7c925282009-03-31 21:38:17 +00001551 return false;
1552 }
1553
Daniel Dunbarb0006ae2009-04-02 15:05:41 +00001554 if (C.getArgs().hasArg(options::OPT__version)) {
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001555 // Follow gcc behavior and use stdout for --version and stderr for -v.
Daniel Dunbar08e41d62009-07-21 20:06:58 +00001556 PrintVersion(C, llvm::outs());
Daniel Dunbarb0006ae2009-04-02 15:05:41 +00001557 return false;
1558 }
1559
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001560 if (C.getArgs().hasArg(options::OPT_v) ||
Daniel Dunbarf0eddb82009-03-18 02:55:38 +00001561 C.getArgs().hasArg(options::OPT__HASH_HASH_HASH)) {
Daniel Dunbar08e41d62009-07-21 20:06:58 +00001562 PrintVersion(C, llvm::errs());
Daniel Dunbar5e0f6af2009-03-13 00:51:18 +00001563 SuppressMissingInputWarning = true;
1564 }
1565
Serge Pavlov208ac652018-01-01 13:27:01 +00001566 if (C.getArgs().hasArg(options::OPT_v)) {
1567 if (!SystemConfigDir.empty())
1568 llvm::errs() << "System configuration file directory: "
1569 << SystemConfigDir << "\n";
1570 if (!UserConfigDir.empty())
1571 llvm::errs() << "User configuration file directory: "
1572 << UserConfigDir << "\n";
1573 }
1574
Daniel Dunbarf0eddb82009-03-18 02:55:38 +00001575 const ToolChain &TC = C.getDefaultToolChain();
Chandler Carruth0ae39aa2013-07-30 17:57:09 +00001576
1577 if (C.getArgs().hasArg(options::OPT_v))
1578 TC.printVerboseInfo(llvm::errs());
1579
Meador Inge51208a32017-04-04 21:46:50 +00001580 if (C.getArgs().hasArg(options::OPT_print_resource_dir)) {
Meador Ingea9113952017-04-05 22:27:20 +00001581 llvm::outs() << ResourceDir << '\n';
Meador Inge51208a32017-04-04 21:46:50 +00001582 return false;
1583 }
1584
Daniel Dunbard972e222009-03-20 04:37:21 +00001585 if (C.getArgs().hasArg(options::OPT_print_search_dirs)) {
1586 llvm::outs() << "programs: =";
Douglas Katzman51fe7bf2015-06-23 22:43:50 +00001587 bool separator = false;
1588 for (const std::string &Path : TC.getProgramPaths()) {
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001589 if (separator)
1590 llvm::outs() << ':';
Douglas Katzman51fe7bf2015-06-23 22:43:50 +00001591 llvm::outs() << Path;
1592 separator = true;
Daniel Dunbard972e222009-03-20 04:37:21 +00001593 }
1594 llvm::outs() << "\n";
Peter Collingbournefa9771f2011-09-06 02:08:31 +00001595 llvm::outs() << "libraries: =" << ResourceDir;
Joerg Sonnenberger9c3e69b2011-07-16 10:50:05 +00001596
Sebastian Pop980920a2012-04-16 04:16:43 +00001597 StringRef sysroot = C.getSysRoot();
Joerg Sonnenberger9c3e69b2011-07-16 10:50:05 +00001598
Douglas Katzman51fe7bf2015-06-23 22:43:50 +00001599 for (const std::string &Path : TC.getFilePaths()) {
1600 // Always print a separator. ResourceDir was the first item shown.
Peter Collingbournefa9771f2011-09-06 02:08:31 +00001601 llvm::outs() << ':';
Douglas Katzman51fe7bf2015-06-23 22:43:50 +00001602 // Interpretation of leading '=' is needed only for NetBSD.
1603 if (Path[0] == '=')
Douglas Katzman26eabf62015-06-24 15:10:30 +00001604 llvm::outs() << sysroot << Path.substr(1);
Joerg Sonnenberger9c3e69b2011-07-16 10:50:05 +00001605 else
Douglas Katzman51fe7bf2015-06-23 22:43:50 +00001606 llvm::outs() << Path;
Daniel Dunbard972e222009-03-20 04:37:21 +00001607 }
1608 llvm::outs() << "\n";
Daniel Dunbar7c925282009-03-31 21:38:17 +00001609 return false;
Daniel Dunbard972e222009-03-20 04:37:21 +00001610 }
1611
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001612 // FIXME: The following handlers should use a callback mechanism, we don't
1613 // know what the client would like to do.
Daniel Dunbarf0eddb82009-03-18 02:55:38 +00001614 if (Arg *A = C.getArgs().getLastArg(options::OPT_print_file_name_EQ)) {
Richard Smithbd55daf2012-11-01 04:30:05 +00001615 llvm::outs() << GetFilePath(A->getValue(), TC) << "\n";
Daniel Dunbar5e0f6af2009-03-13 00:51:18 +00001616 return false;
1617 }
1618
Daniel Dunbarf0eddb82009-03-18 02:55:38 +00001619 if (Arg *A = C.getArgs().getLastArg(options::OPT_print_prog_name_EQ)) {
Saleem Abdulrasoole5f3cf82018-05-01 18:40:42 +00001620 StringRef ProgName = A->getValue();
1621
1622 // Null program name cannot have a path.
1623 if (! ProgName.empty())
1624 llvm::outs() << GetProgramPath(ProgName, TC);
1625
1626 llvm::outs() << "\n";
Daniel Dunbar5e0f6af2009-03-13 00:51:18 +00001627 return false;
1628 }
1629
Yuka Takahashic8068db2017-05-23 18:39:08 +00001630 if (Arg *A = C.getArgs().getLastArg(options::OPT_autocomplete)) {
Yuka Takahashiba5d4af2017-06-20 16:31:31 +00001631 StringRef PassedFlags = A->getValue();
Yuka Takahashi41789e42018-03-05 08:54:20 +00001632 HandleAutocompletions(PassedFlags);
Yuka Takahashic8068db2017-05-23 18:39:08 +00001633 return false;
1634 }
1635
Daniel Dunbarf0eddb82009-03-18 02:55:38 +00001636 if (C.getArgs().hasArg(options::OPT_print_libgcc_file_name)) {
Michal Gorny7cfe4802016-10-10 12:23:40 +00001637 ToolChain::RuntimeLibType RLT = TC.GetRuntimeLibType(C.getArgs());
Leo Li23bb21c2017-08-24 01:51:51 +00001638 const llvm::Triple Triple(TC.ComputeEffectiveClangTriple(C.getArgs()));
1639 RegisterEffectiveTriple TripleRAII(TC, Triple);
Michal Gorny7cfe4802016-10-10 12:23:40 +00001640 switch (RLT) {
1641 case ToolChain::RLT_CompilerRT:
1642 llvm::outs() << TC.getCompilerRT(C.getArgs(), "builtins") << "\n";
1643 break;
1644 case ToolChain::RLT_Libgcc:
1645 llvm::outs() << GetFilePath("libgcc.a", TC) << "\n";
1646 break;
1647 }
Daniel Dunbar5e0f6af2009-03-13 00:51:18 +00001648 return false;
1649 }
1650
Daniel Dunbar1b3ec3a2009-06-16 23:25:22 +00001651 if (C.getArgs().hasArg(options::OPT_print_multi_lib)) {
Douglas Katzmana34b7bf2015-06-30 19:32:57 +00001652 for (const Multilib &Multilib : TC.getMultilibs())
1653 llvm::outs() << Multilib << "\n";
Daniel Dunbar1b3ec3a2009-06-16 23:25:22 +00001654 return false;
1655 }
1656
Jonathan Roelofs2cea1be2014-02-12 03:21:20 +00001657 if (C.getArgs().hasArg(options::OPT_print_multi_directory)) {
Douglas Katzmana34b7bf2015-06-30 19:32:57 +00001658 for (const Multilib &Multilib : TC.getMultilibs()) {
Douglas Katzman6bbffc42015-06-25 18:51:37 +00001659 if (Multilib.gccSuffix().empty())
Jonathan Roelofs2cea1be2014-02-12 03:21:20 +00001660 llvm::outs() << ".\n";
1661 else {
Douglas Katzman6bbffc42015-06-25 18:51:37 +00001662 StringRef Suffix(Multilib.gccSuffix());
Jonathan Roelofs2cea1be2014-02-12 03:21:20 +00001663 assert(Suffix.front() == '/');
1664 llvm::outs() << Suffix.substr(1) << "\n";
1665 }
Jonathan Roelofs3fa96d82014-02-12 01:36:51 +00001666 }
Jonathan Roelofs0e7ec602014-02-12 01:29:25 +00001667 return false;
1668 }
Daniel Dunbar5e0f6af2009-03-13 00:51:18 +00001669 return true;
1670}
1671
Douglas Katzmanfd528672015-06-11 15:05:22 +00001672// Display an action graph human-readably. Action A is the "sink" node
1673// and latest-occuring action. Traversal is in pre-order, visiting the
1674// inputs to each action before printing the action itself.
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001675static unsigned PrintActions1(const Compilation &C, Action *A,
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001676 std::map<Action *, unsigned> &Ids) {
Douglas Katzmanfd528672015-06-11 15:05:22 +00001677 if (Ids.count(A)) // A was already visited.
Daniel Dunbaraaf1ea62009-03-13 12:19:02 +00001678 return Ids[A];
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001679
Daniel Dunbaraaf1ea62009-03-13 12:19:02 +00001680 std::string str;
1681 llvm::raw_string_ostream os(str);
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001682
Daniel Dunbaraaf1ea62009-03-13 12:19:02 +00001683 os << Action::getClassName(A->getKind()) << ", ";
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001684 if (InputAction *IA = dyn_cast<InputAction>(A)) {
Richard Smithbd55daf2012-11-01 04:30:05 +00001685 os << "\"" << IA->getInputArg().getValue() << "\"";
Daniel Dunbaraaf1ea62009-03-13 12:19:02 +00001686 } else if (BindArchAction *BIA = dyn_cast<BindArchAction>(A)) {
Douglas Katzmanb7e8ef02015-06-25 19:37:41 +00001687 os << '"' << BIA->getArchName() << '"' << ", {"
Nico Weber5a459f82016-02-23 19:30:43 +00001688 << PrintActions1(C, *BIA->input_begin(), Ids) << "}";
Samuel Antaod06239d2016-07-15 23:13:27 +00001689 } else if (OffloadAction *OA = dyn_cast<OffloadAction>(A)) {
1690 bool IsFirst = true;
1691 OA->doOnEachDependence(
1692 [&](Action *A, const ToolChain *TC, const char *BoundArch) {
1693 // E.g. for two CUDA device dependences whose bound arch is sm_20 and
1694 // sm_35 this will generate:
1695 // "cuda-device" (nvptx64-nvidia-cuda:sm_20) {#ID}, "cuda-device"
1696 // (nvptx64-nvidia-cuda:sm_35) {#ID}
1697 if (!IsFirst)
1698 os << ", ";
1699 os << '"';
1700 if (TC)
1701 os << A->getOffloadingKindPrefix();
1702 else
1703 os << "host";
1704 os << " (";
1705 os << TC->getTriple().normalize();
1706
1707 if (BoundArch)
1708 os << ":" << BoundArch;
1709 os << ")";
1710 os << '"';
1711 os << " {" << PrintActions1(C, A, Ids) << "}";
1712 IsFirst = false;
1713 });
Daniel Dunbaraaf1ea62009-03-13 12:19:02 +00001714 } else {
Samuel Antaod06239d2016-07-15 23:13:27 +00001715 const ActionList *AL = &A->getInputs();
Artem Belevich0ff05cd2015-07-13 23:27:56 +00001716
Artem Belevich23256752015-09-22 17:23:09 +00001717 if (AL->size()) {
1718 const char *Prefix = "{";
1719 for (Action *PreRequisite : *AL) {
1720 os << Prefix << PrintActions1(C, PreRequisite, Ids);
1721 Prefix = ", ";
1722 }
1723 os << "}";
1724 } else
1725 os << "{}";
Daniel Dunbaraaf1ea62009-03-13 12:19:02 +00001726 }
1727
Samuel Antaod06239d2016-07-15 23:13:27 +00001728 // Append offload info for all options other than the offloading action
1729 // itself (e.g. (cuda-device, sm_20) or (cuda-host)).
1730 std::string offload_str;
1731 llvm::raw_string_ostream offload_os(offload_str);
1732 if (!isa<OffloadAction>(A)) {
1733 auto S = A->getOffloadingKindPrefix();
1734 if (!S.empty()) {
1735 offload_os << ", (" << S;
1736 if (A->getOffloadingArch())
1737 offload_os << ", " << A->getOffloadingArch();
1738 offload_os << ")";
1739 }
1740 }
1741
Daniel Dunbaraaf1ea62009-03-13 12:19:02 +00001742 unsigned Id = Ids.size();
1743 Ids[A] = Id;
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001744 llvm::errs() << Id << ": " << os.str() << ", "
Samuel Antaod06239d2016-07-15 23:13:27 +00001745 << types::getTypeName(A->getType()) << offload_os.str() << "\n";
Daniel Dunbaraaf1ea62009-03-13 12:19:02 +00001746
1747 return Id;
1748}
1749
Douglas Katzmanfd528672015-06-11 15:05:22 +00001750// Print the action graphs in a compilation C.
1751// For example "clang -c file1.c file2.c" is composed of two subgraphs.
Daniel Dunbareb843be2009-03-18 03:13:20 +00001752void Driver::PrintActions(const Compilation &C) const {
Douglas Katzmanb7e8ef02015-06-25 19:37:41 +00001753 std::map<Action *, unsigned> Ids;
1754 for (Action *A : C.getActions())
1755 PrintActions1(C, A, Ids);
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00001756}
1757
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001758/// Check whether the given input tree contains any compilation or
Joerg Sonnenberger5fe4a7d2011-05-06 14:05:11 +00001759/// assembly actions.
1760static bool ContainsCompileOrAssembleAction(const Action *A) {
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001761 if (isa<CompileJobAction>(A) || isa<BackendJobAction>(A) ||
Bob Wilson23a55f12014-12-21 07:00:00 +00001762 isa<AssembleJobAction>(A))
Daniel Dunbar00d3d8e2010-06-29 16:38:33 +00001763 return true;
1764
Nico Weber5a459f82016-02-23 19:30:43 +00001765 for (const Action *Input : A->inputs())
Nico Weberfb80f962015-09-19 21:36:51 +00001766 if (ContainsCompileOrAssembleAction(Input))
Daniel Dunbar00d3d8e2010-06-29 16:38:33 +00001767 return true;
1768
1769 return false;
1770}
1771
Artem Belevich5e2a3ec2015-11-17 22:28:40 +00001772void Driver::BuildUniversalActions(Compilation &C, const ToolChain &TC,
1773 const InputList &BAInputs) const {
1774 DerivedArgList &Args = C.getArgs();
1775 ActionList &Actions = C.getActions();
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001776 llvm::PrettyStackTraceString CrashInfo("Building universal build actions");
1777 // Collect the list of architectures. Duplicates are allowed, but should only
1778 // be handled once (in the order seen).
Daniel Dunbare5dc4822009-03-13 20:33:35 +00001779 llvm::StringSet<> ArchNames;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001780 SmallVector<const char *, 4> Archs;
Saleem Abdulrasool688b6bc2014-12-29 19:01:36 +00001781 for (Arg *A : Args) {
Daniel Dunbar0bfb21e2009-11-19 03:26:40 +00001782 if (A->getOption().matches(options::OPT_arch)) {
Daniel Dunbar9c3f7c42009-09-08 23:37:30 +00001783 // Validate the option here; we don't save the type here because its
1784 // particular spelling may participate in other driver choices.
1785 llvm::Triple::ArchType Arch =
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001786 tools::darwin::getArchTypeForMachOArchName(A->getValue());
Daniel Dunbar9c3f7c42009-09-08 23:37:30 +00001787 if (Arch == llvm::Triple::UnknownArch) {
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001788 Diag(clang::diag::err_drv_invalid_arch_name) << A->getAsString(Args);
Daniel Dunbar9c3f7c42009-09-08 23:37:30 +00001789 continue;
1790 }
1791
Daniel Dunbar2da02722009-03-19 07:55:12 +00001792 A->claim();
David Blaikie61b86d42014-11-19 02:56:13 +00001793 if (ArchNames.insert(A->getValue()).second)
Richard Smithbd55daf2012-11-01 04:30:05 +00001794 Archs.push_back(A->getValue());
Daniel Dunbarf479c122009-03-12 18:40:18 +00001795 }
1796 }
1797
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001798 // When there is no explicit arch for this platform, make sure we still bind
1799 // the architecture (to the default) so that -Xarch_ is handled correctly.
Daniel Dunbareb843be2009-03-18 03:13:20 +00001800 if (!Archs.size())
Daniel Dunbarc3bd9f52012-11-08 03:38:26 +00001801 Archs.push_back(Args.MakeArgString(TC.getDefaultUniversalArchName()));
Daniel Dunbarf479c122009-03-12 18:40:18 +00001802
Daniel Dunbarf479c122009-03-12 18:40:18 +00001803 ActionList SingleActions;
Justin Lebar0f3474c2016-02-11 02:00:50 +00001804 BuildActions(C, Args, BAInputs, SingleActions);
Daniel Dunbarf479c122009-03-12 18:40:18 +00001805
Daniel Dunbar6beaf512010-06-04 18:28:41 +00001806 // Add in arch bindings for every top level action, as well as lipo and
1807 // dsymutil steps if needed.
Nico Weberfb80f962015-09-19 21:36:51 +00001808 for (Action* Act : SingleActions) {
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001809 // Make sure we can lipo this kind of output. If not (and it is an actual
1810 // output) then we disallow, since we can't create an output file with the
1811 // right name without overwriting it. We could remove this oddity by just
1812 // changing the output names to include the arch, which would also fix
Daniel Dunbarf479c122009-03-12 18:40:18 +00001813 // -save-temps. Compatibility wins for now.
1814
Daniel Dunbare2ca3bd2009-03-13 17:46:02 +00001815 if (Archs.size() > 1 && !types::canLipoType(Act->getType()))
Daniel Dunbarf479c122009-03-12 18:40:18 +00001816 Diag(clang::diag::err_drv_invalid_output_with_multiple_archs)
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001817 << types::getTypeName(Act->getType());
Daniel Dunbarf479c122009-03-12 18:40:18 +00001818
1819 ActionList Inputs;
Justin Lebar41094612016-01-11 23:07:27 +00001820 for (unsigned i = 0, e = Archs.size(); i != e; ++i)
1821 Inputs.push_back(C.MakeAction<BindArchAction>(Act, Archs[i]));
Daniel Dunbarf479c122009-03-12 18:40:18 +00001822
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001823 // Lipo if necessary, we do it this way because we need to set the arch flag
1824 // so that -Xarch_ gets overwritten.
Daniel Dunbarf479c122009-03-12 18:40:18 +00001825 if (Inputs.size() == 1 || Act->getType() == types::TY_Nothing)
1826 Actions.append(Inputs.begin(), Inputs.end());
1827 else
Justin Lebar41094612016-01-11 23:07:27 +00001828 Actions.push_back(C.MakeAction<LipoJobAction>(Inputs, Act->getType()));
Daniel Dunbar6beaf512010-06-04 18:28:41 +00001829
Eric Christopher65c05fa2012-02-06 19:43:51 +00001830 // Handle debug info queries.
1831 Arg *A = Args.getLastArg(options::OPT_g_Group);
David Blaikie6f9f4eb2012-04-15 21:22:10 +00001832 if (A && !A->getOption().matches(options::OPT_g0) &&
1833 !A->getOption().matches(options::OPT_gstabs) &&
1834 ContainsCompileOrAssembleAction(Actions.back())) {
Chad Rosier62135492012-07-09 17:31:28 +00001835
David Blaikie6f9f4eb2012-04-15 21:22:10 +00001836 // Add a 'dsymutil' step if necessary, when debug info is enabled and we
1837 // have a compile input. We need to run 'dsymutil' ourselves in such cases
Eric Christopher776c26f2013-01-28 17:39:03 +00001838 // because the debug info will refer to a temporary object file which
David Blaikie6f9f4eb2012-04-15 21:22:10 +00001839 // will be removed at the end of the compilation process.
1840 if (Act->getType() == types::TY_Image) {
1841 ActionList Inputs;
1842 Inputs.push_back(Actions.back());
1843 Actions.pop_back();
Justin Lebar41094612016-01-11 23:07:27 +00001844 Actions.push_back(
1845 C.MakeAction<DsymutilJobAction>(Inputs, types::TY_dSYM));
Daniel Dunbar6beaf512010-06-04 18:28:41 +00001846 }
David Blaikie6f9f4eb2012-04-15 21:22:10 +00001847
Ben Langmuir9b9a8d32014-02-06 18:53:25 +00001848 // Verify the debug info output.
Alp Tokere9d2bfc2014-01-17 02:06:23 +00001849 if (Args.hasArg(options::OPT_verify_debug_info)) {
Justin Lebar41094612016-01-11 23:07:27 +00001850 Action* LastAction = Actions.back();
David Blaikie6f9f4eb2012-04-15 21:22:10 +00001851 Actions.pop_back();
Justin Lebar41094612016-01-11 23:07:27 +00001852 Actions.push_back(C.MakeAction<VerifyDebugInfoJobAction>(
1853 LastAction, types::TY_Nothing));
David Blaikie6f9f4eb2012-04-15 21:22:10 +00001854 }
1855 }
Daniel Dunbarf479c122009-03-12 18:40:18 +00001856 }
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00001857}
1858
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001859/// Check that the file referenced by Value exists. If it doesn't,
Hans Wennborg6ee64d52013-08-06 00:20:31 +00001860/// issue a diagnostic and return false.
Alp Toker8c8a8752013-12-03 06:53:35 +00001861static bool DiagnoseInputExistence(const Driver &D, const DerivedArgList &Args,
Hans Wennborg12f4f8b2016-04-15 01:12:32 +00001862 StringRef Value, types::ID Ty) {
Hans Wennborg6ee64d52013-08-06 00:20:31 +00001863 if (!D.getCheckInputsExist())
1864 return true;
1865
1866 // stdin always exists.
1867 if (Value == "-")
1868 return true;
1869
1870 SmallString<64> Path(Value);
1871 if (Arg *WorkDir = Args.getLastArg(options::OPT_working_directory)) {
Yaron Keren92e1b622015-03-18 10:17:07 +00001872 if (!llvm::sys::path::is_absolute(Path)) {
Hans Wennborg6ee64d52013-08-06 00:20:31 +00001873 SmallString<64> Directory(WorkDir->getValue());
1874 llvm::sys::path::append(Directory, Value);
1875 Path.assign(Directory);
1876 }
1877 }
1878
1879 if (llvm::sys::fs::exists(Twine(Path)))
1880 return true;
1881
Hans Wennborg12f4f8b2016-04-15 01:12:32 +00001882 if (D.IsCLMode()) {
1883 if (!llvm::sys::path::is_absolute(Twine(Path)) &&
1884 llvm::sys::Process::FindInEnvPath("LIB", Value))
1885 return true;
1886
1887 if (Args.hasArg(options::OPT__SLASH_link) && Ty == types::TY_Object) {
1888 // Arguments to the /link flag might cause the linker to search for object
1889 // and library files in paths we don't know about. Don't error in such
1890 // cases.
1891 return true;
1892 }
1893 }
Hans Wennborg23d26a32014-06-18 17:21:50 +00001894
Yaron Keren92e1b622015-03-18 10:17:07 +00001895 D.Diag(clang::diag::err_drv_no_such_file) << Path;
Hans Wennborg6ee64d52013-08-06 00:20:31 +00001896 return false;
1897}
1898
Chad Rosierecdede82011-08-12 22:08:57 +00001899// Construct a the list of inputs and their types.
Hans Wennborg55362852014-05-02 22:55:30 +00001900void Driver::BuildInputs(const ToolChain &TC, DerivedArgList &Args,
Chad Rosierecdede82011-08-12 22:08:57 +00001901 InputList &Inputs) const {
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001902 // Track the current user specified (-x) input. We also explicitly track the
1903 // argument used to set the type; we only want to claim the type when we
1904 // actually use it, so we warn about unused -x arguments.
Daniel Dunbarc5a5ac52009-03-13 17:57:10 +00001905 types::ID InputType = types::TY_Nothing;
Craig Topper92fc2df2014-05-17 16:56:41 +00001906 Arg *InputTypeArg = nullptr;
Daniel Dunbarc5a5ac52009-03-13 17:57:10 +00001907
Hans Wennborg0d0b19c2013-08-12 18:34:17 +00001908 // The last /TC or /TP option sets the input type to C or C++ globally.
Ehsan Akhgaric249abb2014-09-12 21:44:24 +00001909 if (Arg *TCTP = Args.getLastArgNoClaim(options::OPT__SLASH_TC,
1910 options::OPT__SLASH_TP)) {
Hans Wennborg6ee64d52013-08-06 00:20:31 +00001911 InputTypeArg = TCTP;
Hans Wennborg0d0b19c2013-08-12 18:34:17 +00001912 InputType = TCTP->getOption().matches(options::OPT__SLASH_TC)
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001913 ? types::TY_C
1914 : types::TY_CXX;
Hans Wennborg6ee64d52013-08-06 00:20:31 +00001915
Richard Smith0aef3052017-02-18 01:14:43 +00001916 Arg *Previous = nullptr;
Hans Wennborg0d0b19c2013-08-12 18:34:17 +00001917 bool ShowNote = false;
Richard Smith0aef3052017-02-18 01:14:43 +00001918 for (Arg *A : Args.filtered(options::OPT__SLASH_TC, options::OPT__SLASH_TP)) {
1919 if (Previous) {
1920 Diag(clang::diag::warn_drv_overriding_flag_option)
1921 << Previous->getSpelling() << A->getSpelling();
1922 ShowNote = true;
1923 }
1924 Previous = A;
Hans Wennborg6ee64d52013-08-06 00:20:31 +00001925 }
Hans Wennborg0d0b19c2013-08-12 18:34:17 +00001926 if (ShowNote)
1927 Diag(clang::diag::note_drv_t_option_is_global);
Hans Wennborg6ee64d52013-08-06 00:20:31 +00001928
1929 // No driver mode exposes -x and /TC or /TP; we don't support mixing them.
1930 assert(!Args.hasArg(options::OPT_x) && "-x and /TC or /TP is not allowed");
1931 }
1932
Saleem Abdulrasool688b6bc2014-12-29 19:01:36 +00001933 for (Arg *A : Args) {
Michael J. Spencerad3ccc32012-08-20 21:41:17 +00001934 if (A->getOption().getKind() == Option::InputClass) {
Richard Smithbd55daf2012-11-01 04:30:05 +00001935 const char *Value = A->getValue();
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00001936 types::ID Ty = types::TY_INVALID;
1937
1938 // Infer the input type if necessary.
Daniel Dunbarc5a5ac52009-03-13 17:57:10 +00001939 if (InputType == types::TY_Nothing) {
1940 // If there was an explicit arg for this, claim it.
1941 if (InputTypeArg)
1942 InputTypeArg->claim();
1943
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00001944 // stdin must be handled specially.
1945 if (memcmp(Value, "-", 2) == 0) {
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001946 // If running with -E, treat as a C input (this changes the builtin
1947 // macros, for example). This may be overridden by -ObjC below.
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00001948 //
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001949 // Otherwise emit an error but still use a valid type to avoid
1950 // spurious errors (e.g., no inputs).
Hans Wennborg70850d82013-07-18 20:29:38 +00001951 if (!Args.hasArgNoClaim(options::OPT_E) && !CCCIsCPP())
Hans Wennborgcfdd8b52014-01-29 01:04:40 +00001952 Diag(IsCLMode() ? clang::diag::err_drv_unknown_stdin_type_clang_cl
1953 : clang::diag::err_drv_unknown_stdin_type);
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00001954 Ty = types::TY_C;
1955 } else {
Joerg Sonnenbergerbdbdf702011-03-16 22:45:02 +00001956 // Otherwise lookup by extension.
1957 // Fallback is C if invoked as C preprocessor or Object otherwise.
1958 // We use a host hook here because Darwin at least has its own
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001959 // idea of what .s is.
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00001960 if (const char *Ext = strrchr(Value, '.'))
Daniel Dunbarcc7df6c2010-08-02 05:43:56 +00001961 Ty = TC.LookupTypeForExtension(Ext + 1);
Daniel Dunbarea9f0322009-03-20 23:39:23 +00001962
Joerg Sonnenbergerbdbdf702011-03-16 22:45:02 +00001963 if (Ty == types::TY_INVALID) {
Hans Wennborg70850d82013-07-18 20:29:38 +00001964 if (CCCIsCPP())
Joerg Sonnenbergerbdbdf702011-03-16 22:45:02 +00001965 Ty = types::TY_C;
1966 else
1967 Ty = types::TY_Object;
1968 }
Daniel Dunbar0ac94452010-02-17 20:32:58 +00001969
1970 // If the driver is invoked as C++ compiler (like clang++ or c++) it
1971 // should autodetect some input files as C++ for g++ compatibility.
Hans Wennborg70850d82013-07-18 20:29:38 +00001972 if (CCCIsCXX()) {
Daniel Dunbar0ac94452010-02-17 20:32:58 +00001973 types::ID OldTy = Ty;
1974 Ty = types::lookupCXXTypeForCType(Ty);
1975
1976 if (Ty != OldTy)
1977 Diag(clang::diag::warn_drv_treating_input_as_cxx)
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001978 << getTypeName(OldTy) << getTypeName(Ty);
Daniel Dunbar0ac94452010-02-17 20:32:58 +00001979 }
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00001980 }
1981
Daniel Dunbar82b22102009-05-18 21:47:54 +00001982 // -ObjC and -ObjC++ override the default language, but only for "source
1983 // files". We just treat everything that isn't a linker input as a
1984 // source file.
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001985 //
Daniel Dunbar82b22102009-05-18 21:47:54 +00001986 // FIXME: Clean this up if we move the phase sequence into the type.
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00001987 if (Ty != types::TY_Object) {
1988 if (Args.hasArg(options::OPT_ObjC))
1989 Ty = types::TY_ObjC;
1990 else if (Args.hasArg(options::OPT_ObjCXX))
1991 Ty = types::TY_ObjCXX;
1992 }
1993 } else {
1994 assert(InputTypeArg && "InputType set w/o InputTypeArg");
Ehsan Akhgari7e954ea2014-09-12 18:15:10 +00001995 if (!InputTypeArg->getOption().matches(options::OPT_x)) {
1996 // If emulating cl.exe, make sure that /TC and /TP don't affect input
1997 // object files.
1998 const char *Ext = strrchr(Value, '.');
1999 if (Ext && TC.LookupTypeForExtension(Ext + 1) == types::TY_Object)
2000 Ty = types::TY_Object;
2001 }
2002 if (Ty == types::TY_INVALID) {
2003 Ty = InputType;
2004 InputTypeArg->claim();
2005 }
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00002006 }
2007
Hans Wennborg12f4f8b2016-04-15 01:12:32 +00002008 if (DiagnoseInputExistence(*this, Args, Value, Ty))
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00002009 Inputs.push_back(std::make_pair(Ty, A));
2010
Hans Wennborg6ee64d52013-08-06 00:20:31 +00002011 } else if (A->getOption().matches(options::OPT__SLASH_Tc)) {
2012 StringRef Value = A->getValue();
Hans Wennborg12f4f8b2016-04-15 01:12:32 +00002013 if (DiagnoseInputExistence(*this, Args, Value, types::TY_C)) {
David Blaikie0aaa7622017-01-13 17:34:15 +00002014 Arg *InputArg = MakeInputArg(Args, *Opts, A->getValue());
Hans Wennborg6ee64d52013-08-06 00:20:31 +00002015 Inputs.push_back(std::make_pair(types::TY_C, InputArg));
2016 }
2017 A->claim();
2018 } else if (A->getOption().matches(options::OPT__SLASH_Tp)) {
2019 StringRef Value = A->getValue();
Hans Wennborg12f4f8b2016-04-15 01:12:32 +00002020 if (DiagnoseInputExistence(*this, Args, Value, types::TY_CXX)) {
David Blaikie0aaa7622017-01-13 17:34:15 +00002021 Arg *InputArg = MakeInputArg(Args, *Opts, A->getValue());
Hans Wennborg6ee64d52013-08-06 00:20:31 +00002022 Inputs.push_back(std::make_pair(types::TY_CXX, InputArg));
2023 }
2024 A->claim();
Michael J. Spencer66e2b202012-10-19 22:37:06 +00002025 } else if (A->getOption().hasFlag(options::LinkerInput)) {
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00002026 // Just treat as object type, we could make a special type for this if
2027 // necessary.
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00002028 Inputs.push_back(std::make_pair(types::TY_Object, A));
2029
Daniel Dunbar0bfb21e2009-11-19 03:26:40 +00002030 } else if (A->getOption().matches(options::OPT_x)) {
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00002031 InputTypeArg = A;
Richard Smithbd55daf2012-11-01 04:30:05 +00002032 InputType = types::lookupTypeForTypeSpecifier(A->getValue());
Chad Rosier706c2352012-04-07 00:01:31 +00002033 A->claim();
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00002034
2035 // Follow gcc behavior and treat as linker input for invalid -x
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00002036 // options. Its not clear why we shouldn't just revert to unknown; but
Michael J. Spencer1a4fe8c2010-12-17 21:22:33 +00002037 // this isn't very important, we might as well be bug compatible.
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00002038 if (!InputType) {
Richard Smithbd55daf2012-11-01 04:30:05 +00002039 Diag(clang::diag::err_drv_unknown_language) << A->getValue();
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00002040 InputType = types::TY_Object;
2041 }
Hans Wennborg091f1b62017-01-27 17:09:41 +00002042 } else if (A->getOption().getID() == options::OPT__SLASH_U) {
2043 assert(A->getNumValues() == 1 && "The /U option has one value.");
2044 StringRef Val = A->getValue(0);
2045 if (Val.find_first_of("/\\") != StringRef::npos) {
2046 // Warn about e.g. "/Users/me/myfile.c".
2047 Diag(diag::warn_slash_u_filename) << Val;
2048 Diag(diag::note_use_dashdash);
2049 }
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00002050 }
2051 }
Hans Wennborg70850d82013-07-18 20:29:38 +00002052 if (CCCIsCPP() && Inputs.empty()) {
Joerg Sonnenbergerb86f5f42011-03-06 23:31:01 +00002053 // If called as standalone preprocessor, stdin is processed
2054 // if no other input is present.
David Blaikie0aaa7622017-01-13 17:34:15 +00002055 Arg *A = MakeInputArg(Args, *Opts, "-");
Joerg Sonnenbergerb86f5f42011-03-06 23:31:01 +00002056 Inputs.push_back(std::make_pair(types::TY_C, A));
2057 }
Chad Rosierecdede82011-08-12 22:08:57 +00002058}
2059
Samuel Antao64e965e2016-09-30 15:34:19 +00002060namespace {
2061/// Provides a convenient interface for different programming models to generate
2062/// the required device actions.
2063class OffloadingActionBuilder final {
2064 /// Flag used to trace errors in the builder.
2065 bool IsValid = false;
2066
2067 /// The compilation that is using this builder.
2068 Compilation &C;
2069
Samuel Antao64e965e2016-09-30 15:34:19 +00002070 /// Map between an input argument and the offload kinds used to process it.
2071 std::map<const Arg *, unsigned> InputArgToOffloadKindMap;
2072
2073 /// Builder interface. It doesn't build anything or keep any state.
2074 class DeviceActionBuilder {
2075 public:
2076 typedef llvm::SmallVector<phases::ID, phases::MaxNumberOfPhases> PhasesTy;
2077
2078 enum ActionBuilderReturnCode {
2079 // The builder acted successfully on the current action.
2080 ABRT_Success,
2081 // The builder didn't have to act on the current action.
2082 ABRT_Inactive,
2083 // The builder was successful and requested the host action to not be
2084 // generated.
2085 ABRT_Ignore_Host,
2086 };
2087
2088 protected:
2089 /// Compilation associated with this builder.
2090 Compilation &C;
2091
2092 /// Tool chains associated with this builder. The same programming
2093 /// model may have associated one or more tool chains.
2094 SmallVector<const ToolChain *, 2> ToolChains;
2095
2096 /// The derived arguments associated with this builder.
2097 DerivedArgList &Args;
2098
2099 /// The inputs associated with this builder.
2100 const Driver::InputList &Inputs;
2101
2102 /// The associated offload kind.
2103 Action::OffloadKind AssociatedOffloadKind = Action::OFK_None;
2104
2105 public:
2106 DeviceActionBuilder(Compilation &C, DerivedArgList &Args,
2107 const Driver::InputList &Inputs,
2108 Action::OffloadKind AssociatedOffloadKind)
2109 : C(C), Args(Args), Inputs(Inputs),
2110 AssociatedOffloadKind(AssociatedOffloadKind) {}
2111 virtual ~DeviceActionBuilder() {}
2112
2113 /// Fill up the array \a DA with all the device dependences that should be
2114 /// added to the provided host action \a HostAction. By default it is
2115 /// inactive.
2116 virtual ActionBuilderReturnCode
Samuel Antao28c4f182016-10-27 17:08:03 +00002117 getDeviceDependences(OffloadAction::DeviceDependences &DA,
2118 phases::ID CurPhase, phases::ID FinalPhase,
2119 PhasesTy &Phases) {
Samuel Antao64e965e2016-09-30 15:34:19 +00002120 return ABRT_Inactive;
2121 }
2122
2123 /// Update the state to include the provided host action \a HostAction as a
2124 /// dependency of the current device action. By default it is inactive.
2125 virtual ActionBuilderReturnCode addDeviceDepences(Action *HostAction) {
2126 return ABRT_Inactive;
2127 }
2128
2129 /// Append top level actions generated by the builder. Return true if errors
2130 /// were found.
2131 virtual void appendTopLevelActions(ActionList &AL) {}
2132
2133 /// Append linker actions generated by the builder. Return true if errors
2134 /// were found.
2135 virtual void appendLinkDependences(OffloadAction::DeviceDependences &DA) {}
2136
2137 /// Initialize the builder. Return true if any initialization errors are
2138 /// found.
2139 virtual bool initialize() { return false; }
2140
Samuel Antao69d6f312016-10-27 17:50:43 +00002141 /// Return true if the builder can use bundling/unbundling.
2142 virtual bool canUseBundlerUnbundler() const { return false; }
2143
Samuel Antao64e965e2016-09-30 15:34:19 +00002144 /// Return true if this builder is valid. We have a valid builder if we have
2145 /// associated device tool chains.
2146 bool isValid() { return !ToolChains.empty(); }
2147
2148 /// Return the associated offload kind.
2149 Action::OffloadKind getAssociatedOffloadKind() {
2150 return AssociatedOffloadKind;
2151 }
2152 };
2153
Yaxun Liu3af038b2018-05-30 00:49:10 +00002154 /// Base class for CUDA/HIP action builder. It injects device code in
2155 /// the host backend action.
2156 class CudaActionBuilderBase : public DeviceActionBuilder {
2157 protected:
Samuel Antao64e965e2016-09-30 15:34:19 +00002158 /// Flags to signal if the user requested host-only or device-only
2159 /// compilation.
2160 bool CompileHostOnly = false;
2161 bool CompileDeviceOnly = false;
2162
2163 /// List of GPU architectures to use in this compilation.
2164 SmallVector<CudaArch, 4> GpuArchList;
2165
2166 /// The CUDA actions for the current input.
2167 ActionList CudaDeviceActions;
2168
2169 /// The CUDA fat binary if it was generated for the current input.
2170 Action *CudaFatBinary = nullptr;
2171
2172 /// Flag that is set to true if this builder acted on the current input.
2173 bool IsActive = false;
Yaxun Liu3af038b2018-05-30 00:49:10 +00002174 public:
2175 CudaActionBuilderBase(Compilation &C, DerivedArgList &Args,
2176 const Driver::InputList &Inputs,
2177 Action::OffloadKind OFKind)
2178 : DeviceActionBuilder(C, Args, Inputs, OFKind) {}
Samuel Antao64e965e2016-09-30 15:34:19 +00002179
Yaxun Liu3af038b2018-05-30 00:49:10 +00002180 ActionBuilderReturnCode addDeviceDepences(Action *HostAction) override {
2181 // While generating code for CUDA, we only depend on the host input action
2182 // to trigger the creation of all the CUDA device actions.
2183
2184 // If we are dealing with an input action, replicate it for each GPU
2185 // architecture. If we are in host-only mode we return 'success' so that
2186 // the host uses the CUDA offload kind.
2187 if (auto *IA = dyn_cast<InputAction>(HostAction)) {
2188 assert(!GpuArchList.empty() &&
2189 "We should have at least one GPU architecture.");
2190
2191 // If the host input is not CUDA or HIP, we don't need to bother about
2192 // this input.
2193 if (IA->getType() != types::TY_CUDA &&
2194 IA->getType() != types::TY_HIP) {
2195 // The builder will ignore this input.
2196 IsActive = false;
2197 return ABRT_Inactive;
2198 }
2199
2200 // Set the flag to true, so that the builder acts on the current input.
2201 IsActive = true;
2202
2203 if (CompileHostOnly)
2204 return ABRT_Success;
2205
2206 // Replicate inputs for each GPU architecture.
2207 auto Ty = IA->getType() == types::TY_HIP ? types::TY_HIP_DEVICE
2208 : types::TY_CUDA_DEVICE;
2209 for (unsigned I = 0, E = GpuArchList.size(); I != E; ++I) {
2210 CudaDeviceActions.push_back(
2211 C.MakeAction<InputAction>(IA->getInputArg(), Ty));
2212 }
2213
2214 return ABRT_Success;
2215 }
2216
2217 // If this is an unbundling action use it as is for each CUDA toolchain.
2218 if (auto *UA = dyn_cast<OffloadUnbundlingJobAction>(HostAction)) {
2219 CudaDeviceActions.clear();
2220 for (auto Arch : GpuArchList) {
2221 CudaDeviceActions.push_back(UA);
2222 UA->registerDependentActionInfo(ToolChains[0], CudaArchToString(Arch),
2223 AssociatedOffloadKind);
2224 }
2225 return ABRT_Success;
2226 }
2227
2228 return IsActive ? ABRT_Success : ABRT_Inactive;
2229 }
2230
2231 void appendTopLevelActions(ActionList &AL) override {
2232 // Utility to append actions to the top level list.
2233 auto AddTopLevel = [&](Action *A, CudaArch BoundArch) {
2234 OffloadAction::DeviceDependences Dep;
2235 Dep.add(*A, *ToolChains.front(), CudaArchToString(BoundArch),
2236 AssociatedOffloadKind);
2237 AL.push_back(C.MakeAction<OffloadAction>(Dep, A->getType()));
2238 };
2239
2240 // If we have a fat binary, add it to the list.
2241 if (CudaFatBinary) {
2242 AddTopLevel(CudaFatBinary, CudaArch::UNKNOWN);
2243 CudaDeviceActions.clear();
2244 CudaFatBinary = nullptr;
2245 return;
2246 }
2247
2248 if (CudaDeviceActions.empty())
2249 return;
2250
2251 // If we have CUDA actions at this point, that's because we have a have
2252 // partial compilation, so we should have an action for each GPU
2253 // architecture.
2254 assert(CudaDeviceActions.size() == GpuArchList.size() &&
2255 "Expecting one action per GPU architecture.");
2256 assert(ToolChains.size() == 1 &&
2257 "Expecting to have a sing CUDA toolchain.");
2258 for (unsigned I = 0, E = GpuArchList.size(); I != E; ++I)
2259 AddTopLevel(CudaDeviceActions[I], GpuArchList[I]);
2260
2261 CudaDeviceActions.clear();
2262 }
2263
2264 bool initialize() override {
2265 assert(AssociatedOffloadKind == Action::OFK_Cuda ||
2266 AssociatedOffloadKind == Action::OFK_HIP);
2267
2268 // We don't need to support CUDA.
2269 if (AssociatedOffloadKind == Action::OFK_Cuda &&
2270 !C.hasOffloadToolChain<Action::OFK_Cuda>())
2271 return false;
2272
2273 // We don't need to support HIP.
2274 if (AssociatedOffloadKind == Action::OFK_HIP &&
2275 !C.hasOffloadToolChain<Action::OFK_HIP>())
2276 return false;
2277
2278 const ToolChain *HostTC = C.getSingleOffloadToolChain<Action::OFK_Host>();
2279 assert(HostTC && "No toolchain for host compilation.");
2280 if (HostTC->getTriple().isNVPTX() ||
2281 HostTC->getTriple().getArch() == llvm::Triple::amdgcn) {
2282 // We do not support targeting NVPTX/AMDGCN for host compilation. Throw
2283 // an error and abort pipeline construction early so we don't trip
2284 // asserts that assume device-side compilation.
2285 C.getDriver().Diag(diag::err_drv_cuda_host_arch)
2286 << HostTC->getTriple().getArchName();
2287 return true;
2288 }
2289
2290 ToolChains.push_back(
2291 AssociatedOffloadKind == Action::OFK_Cuda
2292 ? C.getSingleOffloadToolChain<Action::OFK_Cuda>()
2293 : C.getSingleOffloadToolChain<Action::OFK_HIP>());
2294
2295 Arg *PartialCompilationArg = Args.getLastArg(
2296 options::OPT_cuda_host_only, options::OPT_cuda_device_only,
2297 options::OPT_cuda_compile_host_device);
2298 CompileHostOnly = PartialCompilationArg &&
2299 PartialCompilationArg->getOption().matches(
2300 options::OPT_cuda_host_only);
2301 CompileDeviceOnly = PartialCompilationArg &&
2302 PartialCompilationArg->getOption().matches(
2303 options::OPT_cuda_device_only);
2304
2305 // Collect all cuda_gpu_arch parameters, removing duplicates.
2306 std::set<CudaArch> GpuArchs;
2307 bool Error = false;
2308 for (Arg *A : Args) {
2309 if (!(A->getOption().matches(options::OPT_cuda_gpu_arch_EQ) ||
2310 A->getOption().matches(options::OPT_no_cuda_gpu_arch_EQ)))
2311 continue;
2312 A->claim();
2313
2314 const StringRef ArchStr = A->getValue();
2315 if (A->getOption().matches(options::OPT_no_cuda_gpu_arch_EQ) &&
2316 ArchStr == "all") {
2317 GpuArchs.clear();
2318 continue;
2319 }
2320 CudaArch Arch = StringToCudaArch(ArchStr);
2321 if (Arch == CudaArch::UNKNOWN) {
2322 C.getDriver().Diag(clang::diag::err_drv_cuda_bad_gpu_arch) << ArchStr;
2323 Error = true;
2324 } else if (A->getOption().matches(options::OPT_cuda_gpu_arch_EQ))
2325 GpuArchs.insert(Arch);
2326 else if (A->getOption().matches(options::OPT_no_cuda_gpu_arch_EQ))
2327 GpuArchs.erase(Arch);
2328 else
2329 llvm_unreachable("Unexpected option.");
2330 }
2331
2332 // Collect list of GPUs remaining in the set.
2333 for (CudaArch Arch : GpuArchs)
2334 GpuArchList.push_back(Arch);
2335
2336 // Default to sm_20 which is the lowest common denominator for
2337 // supported GPUs. sm_20 code should work correctly, if
2338 // suboptimally, on all newer GPUs.
2339 if (GpuArchList.empty())
2340 GpuArchList.push_back(CudaArch::SM_20);
2341
2342 return Error;
2343 }
2344 };
2345
2346 /// \brief CUDA action builder. It injects device code in the host backend
2347 /// action.
2348 class CudaActionBuilder final : public CudaActionBuilderBase {
Samuel Antao64e965e2016-09-30 15:34:19 +00002349 public:
2350 CudaActionBuilder(Compilation &C, DerivedArgList &Args,
2351 const Driver::InputList &Inputs)
Yaxun Liu3af038b2018-05-30 00:49:10 +00002352 : CudaActionBuilderBase(C, Args, Inputs, Action::OFK_Cuda) {}
Samuel Antao64e965e2016-09-30 15:34:19 +00002353
2354 ActionBuilderReturnCode
Samuel Antao28c4f182016-10-27 17:08:03 +00002355 getDeviceDependences(OffloadAction::DeviceDependences &DA,
2356 phases::ID CurPhase, phases::ID FinalPhase,
2357 PhasesTy &Phases) override {
Samuel Antao64e965e2016-09-30 15:34:19 +00002358 if (!IsActive)
2359 return ABRT_Inactive;
2360
2361 // If we don't have more CUDA actions, we don't have any dependences to
2362 // create for the host.
2363 if (CudaDeviceActions.empty())
2364 return ABRT_Success;
2365
2366 assert(CudaDeviceActions.size() == GpuArchList.size() &&
2367 "Expecting one action per GPU architecture.");
2368 assert(!CompileHostOnly &&
2369 "Not expecting CUDA actions in host-only compilation.");
2370
2371 // If we are generating code for the device or we are in a backend phase,
2372 // we attempt to generate the fat binary. We compile each arch to ptx and
2373 // assemble to cubin, then feed the cubin *and* the ptx into a device
2374 // "link" action, which uses fatbinary to combine these cubins into one
2375 // fatbin. The fatbin is then an input to the host action if not in
2376 // device-only mode.
2377 if (CompileDeviceOnly || CurPhase == phases::Backend) {
2378 ActionList DeviceActions;
2379 for (unsigned I = 0, E = GpuArchList.size(); I != E; ++I) {
2380 // Produce the device action from the current phase up to the assemble
2381 // phase.
2382 for (auto Ph : Phases) {
2383 // Skip the phases that were already dealt with.
2384 if (Ph < CurPhase)
2385 continue;
2386 // We have to be consistent with the host final phase.
2387 if (Ph > FinalPhase)
2388 break;
2389
2390 CudaDeviceActions[I] = C.getDriver().ConstructPhaseAction(
Artem Belevichecb178b2018-03-21 22:22:59 +00002391 C, Args, Ph, CudaDeviceActions[I], Action::OFK_Cuda);
Samuel Antao64e965e2016-09-30 15:34:19 +00002392
2393 if (Ph == phases::Assemble)
2394 break;
2395 }
2396
2397 // If we didn't reach the assemble phase, we can't generate the fat
2398 // binary. We don't need to generate the fat binary if we are not in
2399 // device-only mode.
2400 if (!isa<AssembleJobAction>(CudaDeviceActions[I]) ||
2401 CompileDeviceOnly)
2402 continue;
2403
2404 Action *AssembleAction = CudaDeviceActions[I];
2405 assert(AssembleAction->getType() == types::TY_Object);
2406 assert(AssembleAction->getInputs().size() == 1);
2407
2408 Action *BackendAction = AssembleAction->getInputs()[0];
2409 assert(BackendAction->getType() == types::TY_PP_Asm);
2410
2411 for (auto &A : {AssembleAction, BackendAction}) {
2412 OffloadAction::DeviceDependences DDep;
2413 DDep.add(*A, *ToolChains.front(), CudaArchToString(GpuArchList[I]),
2414 Action::OFK_Cuda);
2415 DeviceActions.push_back(
2416 C.MakeAction<OffloadAction>(DDep, A->getType()));
2417 }
2418 }
2419
2420 // We generate the fat binary if we have device input actions.
2421 if (!DeviceActions.empty()) {
2422 CudaFatBinary =
2423 C.MakeAction<LinkJobAction>(DeviceActions, types::TY_CUDA_FATBIN);
2424
2425 if (!CompileDeviceOnly) {
2426 DA.add(*CudaFatBinary, *ToolChains.front(), /*BoundArch=*/nullptr,
2427 Action::OFK_Cuda);
2428 // Clear the fat binary, it is already a dependence to an host
2429 // action.
2430 CudaFatBinary = nullptr;
2431 }
2432
2433 // Remove the CUDA actions as they are already connected to an host
2434 // action or fat binary.
2435 CudaDeviceActions.clear();
2436 }
2437
2438 // We avoid creating host action in device-only mode.
2439 return CompileDeviceOnly ? ABRT_Ignore_Host : ABRT_Success;
Samuel Antao5b1a89a2016-10-27 00:53:34 +00002440 } else if (CurPhase > phases::Backend) {
2441 // If we are past the backend phase and still have a device action, we
2442 // don't have to do anything as this action is already a device
2443 // top-level action.
2444 return ABRT_Success;
Samuel Antao64e965e2016-09-30 15:34:19 +00002445 }
2446
2447 assert(CurPhase < phases::Backend && "Generating single CUDA "
2448 "instructions should only occur "
2449 "before the backend phase!");
2450
2451 // By default, we produce an action for each device arch.
2452 for (Action *&A : CudaDeviceActions)
2453 A = C.getDriver().ConstructPhaseAction(C, Args, CurPhase, A);
2454
2455 return ABRT_Success;
2456 }
Yaxun Liu3af038b2018-05-30 00:49:10 +00002457 };
2458 /// \brief HIP action builder. It injects device code in the host backend
2459 /// action.
2460 class HIPActionBuilder final : public CudaActionBuilderBase {
2461 /// The linker inputs obtained for each device arch.
2462 SmallVector<ActionList, 8> DeviceLinkerInputs;
Samuel Antao64e965e2016-09-30 15:34:19 +00002463
Yaxun Liu3af038b2018-05-30 00:49:10 +00002464 public:
2465 HIPActionBuilder(Compilation &C, DerivedArgList &Args,
2466 const Driver::InputList &Inputs)
2467 : CudaActionBuilderBase(C, Args, Inputs, Action::OFK_HIP) {}
Samuel Antao64e965e2016-09-30 15:34:19 +00002468
Yaxun Liu3af038b2018-05-30 00:49:10 +00002469 bool canUseBundlerUnbundler() const override { return true; }
Samuel Antao64e965e2016-09-30 15:34:19 +00002470
Yaxun Liu3af038b2018-05-30 00:49:10 +00002471 ActionBuilderReturnCode
2472 getDeviceDependences(OffloadAction::DeviceDependences &DA,
2473 phases::ID CurPhase, phases::ID FinalPhase,
2474 PhasesTy &Phases) override {
2475 // amdgcn does not support linking of object files, therefore we skip
2476 // backend and assemble phases to output LLVM IR.
2477 if (CudaDeviceActions.empty() || CurPhase == phases::Backend ||
2478 CurPhase == phases::Assemble)
2479 return ABRT_Success;
2480
2481 assert((CurPhase == phases::Link ||
2482 CudaDeviceActions.size() == GpuArchList.size()) &&
2483 "Expecting one action per GPU architecture.");
2484 assert(!CompileHostOnly &&
2485 "Not expecting CUDA actions in host-only compilation.");
2486
2487 // Save CudaDeviceActions to DeviceLinkerInputs for each GPU subarch.
2488 // This happens to each device action originated from each input file.
2489 // Later on, device actions in DeviceLinkerInputs are used to create
2490 // device link actions in appendLinkDependences and the created device
2491 // link actions are passed to the offload action as device dependence.
2492 if (CurPhase == phases::Link) {
2493 DeviceLinkerInputs.resize(CudaDeviceActions.size());
2494 auto LI = DeviceLinkerInputs.begin();
2495 for (auto *A : CudaDeviceActions) {
2496 LI->push_back(A);
2497 ++LI;
Samuel Antao64e965e2016-09-30 15:34:19 +00002498 }
2499
Yaxun Liu3af038b2018-05-30 00:49:10 +00002500 // We will pass the device action as a host dependence, so we don't
2501 // need to do anything else with them.
2502 CudaDeviceActions.clear();
Samuel Antao64e965e2016-09-30 15:34:19 +00002503 return ABRT_Success;
2504 }
2505
Yaxun Liu3af038b2018-05-30 00:49:10 +00002506 // By default, we produce an action for each device arch.
2507 for (Action *&A : CudaDeviceActions)
2508 A = C.getDriver().ConstructPhaseAction(C, Args, CurPhase, A,
2509 AssociatedOffloadKind);
2510
2511 return ABRT_Success;
Samuel Antao64e965e2016-09-30 15:34:19 +00002512 }
2513
Yaxun Liu3af038b2018-05-30 00:49:10 +00002514 void appendLinkDependences(OffloadAction::DeviceDependences &DA) override {
2515 // Append a new link action for each device.
2516 unsigned I = 0;
2517 for (auto &LI : DeviceLinkerInputs) {
2518 auto *DeviceLinkAction =
2519 C.MakeAction<LinkJobAction>(LI, types::TY_Image);
2520 DA.add(*DeviceLinkAction, *ToolChains[0],
2521 CudaArchToString(GpuArchList[I]), AssociatedOffloadKind);
2522 ++I;
Samuel Antao64e965e2016-09-30 15:34:19 +00002523 }
Samuel Antao64e965e2016-09-30 15:34:19 +00002524 }
2525 };
2526
Samuel Antao28c4f182016-10-27 17:08:03 +00002527 /// OpenMP action builder. The host bitcode is passed to the device frontend
2528 /// and all the device linked images are passed to the host link phase.
2529 class OpenMPActionBuilder final : public DeviceActionBuilder {
2530 /// The OpenMP actions for the current input.
2531 ActionList OpenMPDeviceActions;
2532
2533 /// The linker inputs obtained for each toolchain.
2534 SmallVector<ActionList, 8> DeviceLinkerInputs;
2535
2536 public:
2537 OpenMPActionBuilder(Compilation &C, DerivedArgList &Args,
2538 const Driver::InputList &Inputs)
2539 : DeviceActionBuilder(C, Args, Inputs, Action::OFK_OpenMP) {}
2540
2541 ActionBuilderReturnCode
2542 getDeviceDependences(OffloadAction::DeviceDependences &DA,
2543 phases::ID CurPhase, phases::ID FinalPhase,
2544 PhasesTy &Phases) override {
2545
2546 // We should always have an action for each input.
2547 assert(OpenMPDeviceActions.size() == ToolChains.size() &&
2548 "Number of OpenMP actions and toolchains do not match.");
2549
2550 // The host only depends on device action in the linking phase, when all
2551 // the device images have to be embedded in the host image.
2552 if (CurPhase == phases::Link) {
2553 assert(ToolChains.size() == DeviceLinkerInputs.size() &&
2554 "Toolchains and linker inputs sizes do not match.");
2555 auto LI = DeviceLinkerInputs.begin();
2556 for (auto *A : OpenMPDeviceActions) {
2557 LI->push_back(A);
2558 ++LI;
2559 }
2560
2561 // We passed the device action as a host dependence, so we don't need to
2562 // do anything else with them.
2563 OpenMPDeviceActions.clear();
2564 return ABRT_Success;
2565 }
2566
2567 // By default, we produce an action for each device arch.
2568 for (Action *&A : OpenMPDeviceActions)
2569 A = C.getDriver().ConstructPhaseAction(C, Args, CurPhase, A);
2570
2571 return ABRT_Success;
2572 }
2573
2574 ActionBuilderReturnCode addDeviceDepences(Action *HostAction) override {
2575
2576 // If this is an input action replicate it for each OpenMP toolchain.
2577 if (auto *IA = dyn_cast<InputAction>(HostAction)) {
2578 OpenMPDeviceActions.clear();
2579 for (unsigned I = 0; I < ToolChains.size(); ++I)
2580 OpenMPDeviceActions.push_back(
2581 C.MakeAction<InputAction>(IA->getInputArg(), IA->getType()));
2582 return ABRT_Success;
2583 }
2584
Samuel Antaofab4f372016-10-27 18:00:51 +00002585 // If this is an unbundling action use it as is for each OpenMP toolchain.
2586 if (auto *UA = dyn_cast<OffloadUnbundlingJobAction>(HostAction)) {
2587 OpenMPDeviceActions.clear();
2588 for (unsigned I = 0; I < ToolChains.size(); ++I) {
2589 OpenMPDeviceActions.push_back(UA);
2590 UA->registerDependentActionInfo(
2591 ToolChains[I], /*BoundArch=*/StringRef(), Action::OFK_OpenMP);
2592 }
2593 return ABRT_Success;
2594 }
2595
Samuel Antao28c4f182016-10-27 17:08:03 +00002596 // When generating code for OpenMP we use the host compile phase result as
2597 // a dependence to the device compile phase so that it can learn what
2598 // declarations should be emitted. However, this is not the only use for
2599 // the host action, so we prevent it from being collapsed.
2600 if (isa<CompileJobAction>(HostAction)) {
2601 HostAction->setCannotBeCollapsedWithNextDependentAction();
2602 assert(ToolChains.size() == OpenMPDeviceActions.size() &&
2603 "Toolchains and device action sizes do not match.");
2604 OffloadAction::HostDependence HDep(
2605 *HostAction, *C.getSingleOffloadToolChain<Action::OFK_Host>(),
2606 /*BoundArch=*/nullptr, Action::OFK_OpenMP);
2607 auto TC = ToolChains.begin();
2608 for (Action *&A : OpenMPDeviceActions) {
2609 assert(isa<CompileJobAction>(A));
2610 OffloadAction::DeviceDependences DDep;
2611 DDep.add(*A, **TC, /*BoundArch=*/nullptr, Action::OFK_OpenMP);
2612 A = C.MakeAction<OffloadAction>(HDep, DDep);
2613 ++TC;
2614 }
2615 }
2616 return ABRT_Success;
2617 }
2618
Samuel Antao69d6f312016-10-27 17:50:43 +00002619 void appendTopLevelActions(ActionList &AL) override {
2620 if (OpenMPDeviceActions.empty())
2621 return;
2622
2623 // We should always have an action for each input.
2624 assert(OpenMPDeviceActions.size() == ToolChains.size() &&
2625 "Number of OpenMP actions and toolchains do not match.");
2626
2627 // Append all device actions followed by the proper offload action.
2628 auto TI = ToolChains.begin();
2629 for (auto *A : OpenMPDeviceActions) {
2630 OffloadAction::DeviceDependences Dep;
2631 Dep.add(*A, **TI, /*BoundArch=*/nullptr, Action::OFK_OpenMP);
2632 AL.push_back(C.MakeAction<OffloadAction>(Dep, A->getType()));
2633 ++TI;
2634 }
2635 // We no longer need the action stored in this builder.
2636 OpenMPDeviceActions.clear();
2637 }
2638
Samuel Antao28c4f182016-10-27 17:08:03 +00002639 void appendLinkDependences(OffloadAction::DeviceDependences &DA) override {
2640 assert(ToolChains.size() == DeviceLinkerInputs.size() &&
2641 "Toolchains and linker inputs sizes do not match.");
2642
2643 // Append a new link action for each device.
2644 auto TC = ToolChains.begin();
2645 for (auto &LI : DeviceLinkerInputs) {
2646 auto *DeviceLinkAction =
2647 C.MakeAction<LinkJobAction>(LI, types::TY_Image);
2648 DA.add(*DeviceLinkAction, **TC, /*BoundArch=*/nullptr,
2649 Action::OFK_OpenMP);
2650 ++TC;
2651 }
2652 }
2653
2654 bool initialize() override {
2655 // Get the OpenMP toolchains. If we don't get any, the action builder will
2656 // know there is nothing to do related to OpenMP offloading.
2657 auto OpenMPTCRange = C.getOffloadToolChains<Action::OFK_OpenMP>();
2658 for (auto TI = OpenMPTCRange.first, TE = OpenMPTCRange.second; TI != TE;
2659 ++TI)
2660 ToolChains.push_back(TI->second);
2661
2662 DeviceLinkerInputs.resize(ToolChains.size());
2663 return false;
2664 }
Samuel Antao69d6f312016-10-27 17:50:43 +00002665
2666 bool canUseBundlerUnbundler() const override {
2667 // OpenMP should use bundled files whenever possible.
2668 return true;
2669 }
Samuel Antao28c4f182016-10-27 17:08:03 +00002670 };
2671
2672 ///
2673 /// TODO: Add the implementation for other specialized builders here.
2674 ///
Samuel Antao64e965e2016-09-30 15:34:19 +00002675
2676 /// Specialized builders being used by this offloading action builder.
2677 SmallVector<DeviceActionBuilder *, 4> SpecializedBuilders;
2678
Samuel Antao69d6f312016-10-27 17:50:43 +00002679 /// Flag set to true if all valid builders allow file bundling/unbundling.
2680 bool CanUseBundler;
2681
Samuel Antao64e965e2016-09-30 15:34:19 +00002682public:
2683 OffloadingActionBuilder(Compilation &C, DerivedArgList &Args,
2684 const Driver::InputList &Inputs)
Samuel Antao10e905c2016-10-27 01:08:58 +00002685 : C(C) {
Samuel Antao64e965e2016-09-30 15:34:19 +00002686 // Create a specialized builder for each device toolchain.
2687
2688 IsValid = true;
2689
2690 // Create a specialized builder for CUDA.
2691 SpecializedBuilders.push_back(new CudaActionBuilder(C, Args, Inputs));
2692
Yaxun Liu3af038b2018-05-30 00:49:10 +00002693 // Create a specialized builder for HIP.
2694 SpecializedBuilders.push_back(new HIPActionBuilder(C, Args, Inputs));
2695
Samuel Antao28c4f182016-10-27 17:08:03 +00002696 // Create a specialized builder for OpenMP.
2697 SpecializedBuilders.push_back(new OpenMPActionBuilder(C, Args, Inputs));
2698
Samuel Antao64e965e2016-09-30 15:34:19 +00002699 //
2700 // TODO: Build other specialized builders here.
2701 //
2702
Samuel Antao69d6f312016-10-27 17:50:43 +00002703 // Initialize all the builders, keeping track of errors. If all valid
2704 // builders agree that we can use bundling, set the flag to true.
2705 unsigned ValidBuilders = 0u;
2706 unsigned ValidBuildersSupportingBundling = 0u;
2707 for (auto *SB : SpecializedBuilders) {
Samuel Antao64e965e2016-09-30 15:34:19 +00002708 IsValid = IsValid && !SB->initialize();
Samuel Antao69d6f312016-10-27 17:50:43 +00002709
2710 // Update the counters if the builder is valid.
2711 if (SB->isValid()) {
2712 ++ValidBuilders;
2713 if (SB->canUseBundlerUnbundler())
2714 ++ValidBuildersSupportingBundling;
2715 }
2716 }
2717 CanUseBundler =
2718 ValidBuilders && ValidBuilders == ValidBuildersSupportingBundling;
Artem Belevichf981e30b2016-08-02 22:37:47 +00002719 }
Justin Lebardc3c5042016-04-19 02:27:07 +00002720
Samuel Antao64e965e2016-09-30 15:34:19 +00002721 ~OffloadingActionBuilder() {
2722 for (auto *SB : SpecializedBuilders)
2723 delete SB;
Samuel Antaod06239d2016-07-15 23:13:27 +00002724 }
Artem Belevich0ff05cd2015-07-13 23:27:56 +00002725
Samuel Antao64e965e2016-09-30 15:34:19 +00002726 /// Generate an action that adds device dependences (if any) to a host action.
2727 /// If no device dependence actions exist, just return the host action \a
2728 /// HostAction. If an error is found or if no builder requires the host action
2729 /// to be generated, return nullptr.
2730 Action *
2731 addDeviceDependencesToHostAction(Action *HostAction, const Arg *InputArg,
2732 phases::ID CurPhase, phases::ID FinalPhase,
2733 DeviceActionBuilder::PhasesTy &Phases) {
2734 if (!IsValid)
2735 return nullptr;
Justin Lebar7bf77982016-01-11 23:27:13 +00002736
Samuel Antao64e965e2016-09-30 15:34:19 +00002737 if (SpecializedBuilders.empty())
2738 return HostAction;
2739
2740 assert(HostAction && "Invalid host action!");
2741
2742 OffloadAction::DeviceDependences DDeps;
2743 // Check if all the programming models agree we should not emit the host
2744 // action. Also, keep track of the offloading kinds employed.
2745 auto &OffloadKind = InputArgToOffloadKindMap[InputArg];
2746 unsigned InactiveBuilders = 0u;
2747 unsigned IgnoringBuilders = 0u;
2748 for (auto *SB : SpecializedBuilders) {
2749 if (!SB->isValid()) {
2750 ++InactiveBuilders;
2751 continue;
2752 }
2753
Samuel Antao28c4f182016-10-27 17:08:03 +00002754 auto RetCode =
2755 SB->getDeviceDependences(DDeps, CurPhase, FinalPhase, Phases);
Samuel Antao64e965e2016-09-30 15:34:19 +00002756
2757 // If the builder explicitly says the host action should be ignored,
2758 // we need to increment the variable that tracks the builders that request
2759 // the host object to be ignored.
2760 if (RetCode == DeviceActionBuilder::ABRT_Ignore_Host)
2761 ++IgnoringBuilders;
2762
2763 // Unless the builder was inactive for this action, we have to record the
2764 // offload kind because the host will have to use it.
2765 if (RetCode != DeviceActionBuilder::ABRT_Inactive)
2766 OffloadKind |= SB->getAssociatedOffloadKind();
2767 }
2768
2769 // If all builders agree that the host object should be ignored, just return
2770 // nullptr.
2771 if (IgnoringBuilders &&
2772 SpecializedBuilders.size() == (InactiveBuilders + IgnoringBuilders))
2773 return nullptr;
2774
2775 if (DDeps.getActions().empty())
2776 return HostAction;
2777
2778 // We have dependences we need to bundle together. We use an offload action
2779 // for that.
2780 OffloadAction::HostDependence HDep(
2781 *HostAction, *C.getSingleOffloadToolChain<Action::OFK_Host>(),
2782 /*BoundArch=*/nullptr, DDeps);
2783 return C.MakeAction<OffloadAction>(HDep, DDeps);
Artem Belevich0ff05cd2015-07-13 23:27:56 +00002784 }
2785
Samuel Antao64e965e2016-09-30 15:34:19 +00002786 /// Generate an action that adds a host dependence to a device action. The
2787 /// results will be kept in this action builder. Return true if an error was
2788 /// found.
Samuel Antaofab4f372016-10-27 18:00:51 +00002789 bool addHostDependenceToDeviceActions(Action *&HostAction,
Samuel Antao64e965e2016-09-30 15:34:19 +00002790 const Arg *InputArg) {
2791 if (!IsValid)
2792 return true;
Artem Belevich0ff05cd2015-07-13 23:27:56 +00002793
Samuel Antaofab4f372016-10-27 18:00:51 +00002794 // If we are supporting bundling/unbundling and the current action is an
2795 // input action of non-source file, we replace the host action by the
2796 // unbundling action. The bundler tool has the logic to detect if an input
2797 // is a bundle or not and if the input is not a bundle it assumes it is a
2798 // host file. Therefore it is safe to create an unbundling action even if
2799 // the input is not a bundle.
2800 if (CanUseBundler && isa<InputAction>(HostAction) &&
2801 InputArg->getOption().getKind() == llvm::opt::Option::InputClass &&
2802 !types::isSrcFile(HostAction->getType())) {
2803 auto UnbundlingHostAction =
2804 C.MakeAction<OffloadUnbundlingJobAction>(HostAction);
2805 UnbundlingHostAction->registerDependentActionInfo(
2806 C.getSingleOffloadToolChain<Action::OFK_Host>(),
2807 /*BoundArch=*/StringRef(), Action::OFK_Host);
2808 HostAction = UnbundlingHostAction;
2809 }
2810
Samuel Antao64e965e2016-09-30 15:34:19 +00002811 assert(HostAction && "Invalid host action!");
Artem Belevich0ff05cd2015-07-13 23:27:56 +00002812
Samuel Antao64e965e2016-09-30 15:34:19 +00002813 // Register the offload kinds that are used.
2814 auto &OffloadKind = InputArgToOffloadKindMap[InputArg];
2815 for (auto *SB : SpecializedBuilders) {
2816 if (!SB->isValid())
2817 continue;
Artem Belevich0ff05cd2015-07-13 23:27:56 +00002818
Samuel Antao64e965e2016-09-30 15:34:19 +00002819 auto RetCode = SB->addDeviceDepences(HostAction);
Artem Belevich0ff05cd2015-07-13 23:27:56 +00002820
Samuel Antao64e965e2016-09-30 15:34:19 +00002821 // Host dependences for device actions are not compatible with that same
2822 // action being ignored.
2823 assert(RetCode != DeviceActionBuilder::ABRT_Ignore_Host &&
2824 "Host dependence not expected to be ignored.!");
Samuel Antaod06239d2016-07-15 23:13:27 +00002825
Samuel Antao64e965e2016-09-30 15:34:19 +00002826 // Unless the builder was inactive for this action, we have to record the
2827 // offload kind because the host will have to use it.
2828 if (RetCode != DeviceActionBuilder::ABRT_Inactive)
2829 OffloadKind |= SB->getAssociatedOffloadKind();
2830 }
Artem Belevich0ff05cd2015-07-13 23:27:56 +00002831
Samuel Antao64e965e2016-09-30 15:34:19 +00002832 return false;
2833 }
2834
Samuel Antao69d6f312016-10-27 17:50:43 +00002835 /// Add the offloading top level actions to the provided action list. This
2836 /// function can replace the host action by a bundling action if the
2837 /// programming models allow it.
Samuel Antao64e965e2016-09-30 15:34:19 +00002838 bool appendTopLevelActions(ActionList &AL, Action *HostAction,
2839 const Arg *InputArg) {
Samuel Antao69d6f312016-10-27 17:50:43 +00002840 // Get the device actions to be appended.
2841 ActionList OffloadAL;
Samuel Antao64e965e2016-09-30 15:34:19 +00002842 for (auto *SB : SpecializedBuilders) {
2843 if (!SB->isValid())
2844 continue;
Samuel Antao69d6f312016-10-27 17:50:43 +00002845 SB->appendTopLevelActions(OffloadAL);
Samuel Antao64e965e2016-09-30 15:34:19 +00002846 }
2847
Samuel Antao69d6f312016-10-27 17:50:43 +00002848 // If we can use the bundler, replace the host action by the bundling one in
2849 // the resulting list. Otherwise, just append the device actions.
2850 if (CanUseBundler && !OffloadAL.empty()) {
2851 // Add the host action to the list in order to create the bundling action.
2852 OffloadAL.push_back(HostAction);
2853
2854 // We expect that the host action was just appended to the action list
2855 // before this method was called.
2856 assert(HostAction == AL.back() && "Host action not in the list??");
2857 HostAction = C.MakeAction<OffloadBundlingJobAction>(OffloadAL);
2858 AL.back() = HostAction;
2859 } else
2860 AL.append(OffloadAL.begin(), OffloadAL.end());
2861
Samuel Antao64e965e2016-09-30 15:34:19 +00002862 // Propagate to the current host action (if any) the offload information
2863 // associated with the current input.
2864 if (HostAction)
2865 HostAction->propagateHostOffloadInfo(InputArgToOffloadKindMap[InputArg],
2866 /*BoundArch=*/nullptr);
Samuel Antao64e965e2016-09-30 15:34:19 +00002867 return false;
Artem Belevich0ff05cd2015-07-13 23:27:56 +00002868 }
Artem Belevich5bde4e02015-07-20 20:02:54 +00002869
Samuel Antao64e965e2016-09-30 15:34:19 +00002870 /// Processes the host linker action. This currently consists of replacing it
2871 /// with an offload action if there are device link objects and propagate to
2872 /// the host action all the offload kinds used in the current compilation. The
2873 /// resulting action is returned.
2874 Action *processHostLinkAction(Action *HostAction) {
2875 // Add all the dependences from the device linking actions.
2876 OffloadAction::DeviceDependences DDeps;
2877 for (auto *SB : SpecializedBuilders) {
2878 if (!SB->isValid())
2879 continue;
Justin Lebar21e5d4f2016-01-14 21:41:27 +00002880
Samuel Antao64e965e2016-09-30 15:34:19 +00002881 SB->appendLinkDependences(DDeps);
Justin Lebar21e5d4f2016-01-14 21:41:27 +00002882 }
Samuel Antaod06239d2016-07-15 23:13:27 +00002883
Samuel Antao64e965e2016-09-30 15:34:19 +00002884 // Calculate all the offload kinds used in the current compilation.
2885 unsigned ActiveOffloadKinds = 0u;
2886 for (auto &I : InputArgToOffloadKindMap)
2887 ActiveOffloadKinds |= I.second;
2888
2889 // If we don't have device dependencies, we don't have to create an offload
2890 // action.
2891 if (DDeps.getActions().empty()) {
2892 // Propagate all the active kinds to host action. Given that it is a link
2893 // action it is assumed to depend on all actions generated so far.
2894 HostAction->propagateHostOffloadInfo(ActiveOffloadKinds,
2895 /*BoundArch=*/nullptr);
2896 return HostAction;
2897 }
2898
2899 // Create the offload action with all dependences. When an offload action
2900 // is created the kinds are propagated to the host action, so we don't have
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00002901 // to do that explicitly here.
Samuel Antao64e965e2016-09-30 15:34:19 +00002902 OffloadAction::HostDependence HDep(
2903 *HostAction, *C.getSingleOffloadToolChain<Action::OFK_Host>(),
2904 /*BoundArch*/ nullptr, ActiveOffloadKinds);
2905 return C.MakeAction<OffloadAction>(HDep, DDeps);
2906 }
2907};
2908} // anonymous namespace.
Artem Belevich0ff05cd2015-07-13 23:27:56 +00002909
Justin Lebar0f3474c2016-02-11 02:00:50 +00002910void Driver::BuildActions(Compilation &C, DerivedArgList &Args,
2911 const InputList &Inputs, ActionList &Actions) const {
Chad Rosierecdede82011-08-12 22:08:57 +00002912 llvm::PrettyStackTraceString CrashInfo("Building compilation actions");
Joerg Sonnenbergerb86f5f42011-03-06 23:31:01 +00002913
Daniel Dunbar34c41872009-03-13 00:17:48 +00002914 if (!SuppressMissingInputWarning && Inputs.empty()) {
Daniel Dunbarbfeec742009-03-12 23:55:14 +00002915 Diag(clang::diag::err_drv_no_input_files);
2916 return;
2917 }
2918
Chad Rosier7742b5d2011-07-27 23:36:45 +00002919 Arg *FinalPhaseArg;
2920 phases::ID FinalPhase = getFinalPhase(Args, &FinalPhaseArg);
Daniel Dunbarbfeec742009-03-12 23:55:14 +00002921
Bob Haarmanaaf51912017-02-27 19:40:19 +00002922 if (FinalPhase == phases::Link) {
2923 if (Args.hasArg(options::OPT_emit_llvm))
2924 Diag(clang::diag::err_drv_emit_llvm_link);
2925 if (IsCLMode() && LTOMode != LTOK_None &&
2926 !Args.getLastArgValue(options::OPT_fuse_ld_EQ).equals_lower("lld"))
2927 Diag(clang::diag::err_drv_lto_without_lld);
Rafael Espindolae8025642013-08-25 14:27:09 +00002928 }
2929
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00002930 // Reject -Z* at the top level, these options should never have been exposed
2931 // by gcc.
Daniel Dunbardd765242009-03-26 16:12:09 +00002932 if (Arg *A = Args.getLastArg(options::OPT_Z_Joined))
Daniel Dunbar0e759942009-03-20 06:14:23 +00002933 Diag(clang::diag::err_drv_use_of_Z_option) << A->getAsString(Args);
Daniel Dunbarbfeec742009-03-12 23:55:14 +00002934
Hans Wennborg13b7fe72013-08-12 23:26:25 +00002935 // Diagnose misuse of /Fo.
2936 if (Arg *A = Args.getLastArg(options::OPT__SLASH_Fo)) {
Hans Wennborg13b7fe72013-08-12 23:26:25 +00002937 StringRef V = A->getValue();
Hans Wennborg61647532014-11-17 19:16:36 +00002938 if (Inputs.size() > 1 && !V.empty() &&
2939 !llvm::sys::path::is_separator(V.back())) {
Hans Wennborg13b7fe72013-08-12 23:26:25 +00002940 // Check whether /Fo tries to name an output file for multiple inputs.
Hans Wennborg9c1659b2013-10-18 22:49:04 +00002941 Diag(clang::diag::err_drv_out_file_argument_with_multiple_sources)
Douglas Katzmana67e50c2015-06-26 15:47:46 +00002942 << A->getSpelling() << V;
Hans Wennborg13b7fe72013-08-12 23:26:25 +00002943 Args.eraseArg(options::OPT__SLASH_Fo);
2944 }
2945 }
2946
Hans Wennborg9c1659b2013-10-18 22:49:04 +00002947 // Diagnose misuse of /Fa.
2948 if (Arg *A = Args.getLastArg(options::OPT__SLASH_Fa)) {
2949 StringRef V = A->getValue();
Hans Wennborg61647532014-11-17 19:16:36 +00002950 if (Inputs.size() > 1 && !V.empty() &&
2951 !llvm::sys::path::is_separator(V.back())) {
Hans Wennborg9c1659b2013-10-18 22:49:04 +00002952 // Check whether /Fa tries to name an asm file for multiple inputs.
2953 Diag(clang::diag::err_drv_out_file_argument_with_multiple_sources)
Douglas Katzmana67e50c2015-06-26 15:47:46 +00002954 << A->getSpelling() << V;
Hans Wennborg9c1659b2013-10-18 22:49:04 +00002955 Args.eraseArg(options::OPT__SLASH_Fa);
2956 }
2957 }
2958
Ehsan Akhgari81f36b72014-09-11 18:16:21 +00002959 // Diagnose misuse of /o.
2960 if (Arg *A = Args.getLastArg(options::OPT__SLASH_o)) {
2961 if (A->getValue()[0] == '\0') {
2962 // It has to have a value.
2963 Diag(clang::diag::err_drv_missing_argument) << A->getSpelling() << 1;
2964 Args.eraseArg(options::OPT__SLASH_o);
2965 }
2966 }
2967
Nico Weber2ca4be92016-03-01 23:16:44 +00002968 // Diagnose unsupported forms of /Yc /Yu. Ignore /Yc/Yu for now if:
2969 // * no filename after it
2970 // * both /Yc and /Yu passed but with different filenames
2971 // * corresponding file not also passed as /FI
2972 Arg *YcArg = Args.getLastArg(options::OPT__SLASH_Yc);
2973 Arg *YuArg = Args.getLastArg(options::OPT__SLASH_Yu);
2974 if (YcArg && YcArg->getValue()[0] == '\0') {
2975 Diag(clang::diag::warn_drv_ycyu_no_arg_clang_cl) << YcArg->getSpelling();
2976 Args.eraseArg(options::OPT__SLASH_Yc);
2977 YcArg = nullptr;
2978 }
2979 if (YuArg && YuArg->getValue()[0] == '\0') {
2980 Diag(clang::diag::warn_drv_ycyu_no_arg_clang_cl) << YuArg->getSpelling();
2981 Args.eraseArg(options::OPT__SLASH_Yu);
2982 YuArg = nullptr;
2983 }
2984 if (YcArg && YuArg && strcmp(YcArg->getValue(), YuArg->getValue()) != 0) {
2985 Diag(clang::diag::warn_drv_ycyu_different_arg_clang_cl);
2986 Args.eraseArg(options::OPT__SLASH_Yc);
2987 Args.eraseArg(options::OPT__SLASH_Yu);
2988 YcArg = YuArg = nullptr;
2989 }
2990 if (YcArg || YuArg) {
2991 StringRef Val = YcArg ? YcArg->getValue() : YuArg->getValue();
2992 bool FoundMatchingInclude = false;
2993 for (const Arg *Inc : Args.filtered(options::OPT_include)) {
2994 // FIXME: Do case-insensitive matching and consider / and \ as equal.
2995 if (Inc->getValue() == Val)
2996 FoundMatchingInclude = true;
2997 }
2998 if (!FoundMatchingInclude) {
2999 Diag(clang::diag::warn_drv_ycyu_no_fi_arg_clang_cl)
3000 << (YcArg ? YcArg : YuArg)->getSpelling();
3001 Args.eraseArg(options::OPT__SLASH_Yc);
3002 Args.eraseArg(options::OPT__SLASH_Yu);
3003 YcArg = YuArg = nullptr;
3004 }
3005 }
3006 if (YcArg && Inputs.size() > 1) {
3007 Diag(clang::diag::warn_drv_yc_multiple_inputs_clang_cl);
3008 Args.eraseArg(options::OPT__SLASH_Yc);
3009 YcArg = nullptr;
3010 }
3011 if (Args.hasArg(options::OPT__SLASH_Y_)) {
3012 // /Y- disables all pch handling. Rather than check for it everywhere,
3013 // just remove clang-cl pch-related flags here.
3014 Args.eraseArg(options::OPT__SLASH_Fp);
3015 Args.eraseArg(options::OPT__SLASH_Yc);
3016 Args.eraseArg(options::OPT__SLASH_Yu);
3017 YcArg = YuArg = nullptr;
3018 }
Nico Weber2ca4be92016-03-01 23:16:44 +00003019
Samuel Antao64e965e2016-09-30 15:34:19 +00003020 // Builder to be used to build offloading actions.
3021 OffloadingActionBuilder OffloadBuilder(C, Args, Inputs);
Samuel Antaod06239d2016-07-15 23:13:27 +00003022
Daniel Dunbar65229332009-03-13 11:38:42 +00003023 // Construct the actions to perform.
3024 ActionList LinkerInputs;
Alp Toker965f8822013-11-27 05:22:15 +00003025
Matthew Curtis7ab8b2b2013-03-07 12:32:26 +00003026 llvm::SmallVector<phases::ID, phases::MaxNumberOfPhases> PL;
Artem Belevich5bde4e02015-07-20 20:02:54 +00003027 for (auto &I : Inputs) {
3028 types::ID InputType = I.first;
3029 const Arg *InputArg = I.second;
Daniel Dunbar65229332009-03-13 11:38:42 +00003030
Matthew Curtis7ab8b2b2013-03-07 12:32:26 +00003031 PL.clear();
3032 types::getCompilationPhases(InputType, PL);
Daniel Dunbar65229332009-03-13 11:38:42 +00003033
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00003034 // If the first step comes after the final phase we are doing as part of
3035 // this compilation, warn the user about it.
Matthew Curtis7ab8b2b2013-03-07 12:32:26 +00003036 phases::ID InitialPhase = PL[0];
Daniel Dunbar65229332009-03-13 11:38:42 +00003037 if (InitialPhase > FinalPhase) {
Martin Storsjo665c7a42018-05-04 06:05:58 +00003038 if (InputArg->isClaimed())
3039 continue;
3040
Daniel Dunbaradc5c7c2009-03-19 07:57:08 +00003041 // Claim here to avoid the more general unused warning.
3042 InputArg->claim();
Daniel Dunbar07806ca2009-09-17 04:13:26 +00003043
Daniel Dunbar2db3e732011-04-20 15:44:48 +00003044 // Suppress all unused style warnings with -Qunused-arguments
3045 if (Args.hasArg(options::OPT_Qunused_arguments))
3046 continue;
3047
Richard Smith403f76e2012-08-06 04:09:06 +00003048 // Special case when final phase determined by binary name, rather than
3049 // by a command-line argument with a corresponding Arg.
Hans Wennborg70850d82013-07-18 20:29:38 +00003050 if (CCCIsCPP())
Richard Smith403f76e2012-08-06 04:09:06 +00003051 Diag(clang::diag::warn_drv_input_file_unused_by_cpp)
Douglas Katzmana67e50c2015-06-26 15:47:46 +00003052 << InputArg->getAsString(Args) << getPhaseName(InitialPhase);
Daniel Dunbar07806ca2009-09-17 04:13:26 +00003053 // Special case '-E' warning on a previously preprocessed file to make
3054 // more sense.
Richard Smith403f76e2012-08-06 04:09:06 +00003055 else if (InitialPhase == phases::Compile &&
3056 FinalPhase == phases::Preprocess &&
3057 getPreprocessedType(InputType) == types::TY_INVALID)
Daniel Dunbar07806ca2009-09-17 04:13:26 +00003058 Diag(clang::diag::warn_drv_preprocessed_input_file_unused)
Douglas Katzmana67e50c2015-06-26 15:47:46 +00003059 << InputArg->getAsString(Args) << !!FinalPhaseArg
3060 << (FinalPhaseArg ? FinalPhaseArg->getOption().getName() : "");
Daniel Dunbar07806ca2009-09-17 04:13:26 +00003061 else
3062 Diag(clang::diag::warn_drv_input_file_unused)
Douglas Katzmana67e50c2015-06-26 15:47:46 +00003063 << InputArg->getAsString(Args) << getPhaseName(InitialPhase)
3064 << !!FinalPhaseArg
3065 << (FinalPhaseArg ? FinalPhaseArg->getOption().getName() : "");
Daniel Dunbar65229332009-03-13 11:38:42 +00003066 continue;
3067 }
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00003068
Nico Weberad2d8f32016-04-21 19:59:10 +00003069 if (YcArg) {
3070 // Add a separate precompile phase for the compile phase.
3071 if (FinalPhase >= phases::Compile) {
Richard Smith8cd452d2016-08-30 18:55:16 +00003072 const types::ID HeaderType = lookupHeaderTypeForSourceType(InputType);
Nico Weberad2d8f32016-04-21 19:59:10 +00003073 llvm::SmallVector<phases::ID, phases::MaxNumberOfPhases> PCHPL;
Richard Smith8cd452d2016-08-30 18:55:16 +00003074 types::getCompilationPhases(HeaderType, PCHPL);
David Blaikie0aaa7622017-01-13 17:34:15 +00003075 Arg *PchInputArg = MakeInputArg(Args, *Opts, YcArg->getValue());
Nico Weberad2d8f32016-04-21 19:59:10 +00003076
3077 // Build the pipeline for the pch file.
Richard Smith8cd452d2016-08-30 18:55:16 +00003078 Action *ClangClPch =
3079 C.MakeAction<InputAction>(*PchInputArg, HeaderType);
Nico Weberad2d8f32016-04-21 19:59:10 +00003080 for (phases::ID Phase : PCHPL)
3081 ClangClPch = ConstructPhaseAction(C, Args, Phase, ClangClPch);
3082 assert(ClangClPch);
3083 Actions.push_back(ClangClPch);
3084 // The driver currently exits after the first failed command. This
3085 // relies on that behavior, to make sure if the pch generation fails,
3086 // the main compilation won't run.
3087 }
3088 }
3089
Daniel Dunbar65229332009-03-13 11:38:42 +00003090 // Build the pipeline for this file.
Justin Lebar41094612016-01-11 23:07:27 +00003091 Action *Current = C.MakeAction<InputAction>(*InputArg, InputType);
Samuel Antao64e965e2016-09-30 15:34:19 +00003092
3093 // Use the current host action in any of the offloading actions, if
3094 // required.
3095 if (OffloadBuilder.addHostDependenceToDeviceActions(Current, InputArg))
3096 break;
3097
Douglas Katzmana67e50c2015-06-26 15:47:46 +00003098 for (SmallVectorImpl<phases::ID>::iterator i = PL.begin(), e = PL.end();
3099 i != e; ++i) {
Matthew Curtis7ab8b2b2013-03-07 12:32:26 +00003100 phases::ID Phase = *i;
Daniel Dunbar65229332009-03-13 11:38:42 +00003101
3102 // We are done if this step is past what the user requested.
3103 if (Phase > FinalPhase)
3104 break;
3105
Samuel Antao64e965e2016-09-30 15:34:19 +00003106 // Add any offload action the host action depends on.
3107 Current = OffloadBuilder.addDeviceDependencesToHostAction(
3108 Current, InputArg, Phase, FinalPhase, PL);
3109 if (!Current)
3110 break;
3111
Daniel Dunbar65229332009-03-13 11:38:42 +00003112 // Queue linker inputs.
3113 if (Phase == phases::Link) {
Matthew Curtis7ab8b2b2013-03-07 12:32:26 +00003114 assert((i + 1) == e && "linking must be final compilation step.");
Justin Lebar41094612016-01-11 23:07:27 +00003115 LinkerInputs.push_back(Current);
3116 Current = nullptr;
Daniel Dunbar65229332009-03-13 11:38:42 +00003117 break;
3118 }
3119
Samuel Antao64e965e2016-09-30 15:34:19 +00003120 // Otherwise construct the appropriate action.
3121 auto *NewCurrent = ConstructPhaseAction(C, Args, Phase, Current);
3122
3123 // We didn't create a new action, so we will just move to the next phase.
3124 if (NewCurrent == Current)
Daniel Dunbar13864952009-03-24 20:17:30 +00003125 continue;
3126
Samuel Antao64e965e2016-09-30 15:34:19 +00003127 Current = NewCurrent;
Artem Belevich0ff05cd2015-07-13 23:27:56 +00003128
Samuel Antao64e965e2016-09-30 15:34:19 +00003129 // Use the current host action in any of the offloading actions, if
3130 // required.
3131 if (OffloadBuilder.addHostDependenceToDeviceActions(Current, InputArg))
3132 break;
Artem Belevich0ff05cd2015-07-13 23:27:56 +00003133
Daniel Dunbar65229332009-03-13 11:38:42 +00003134 if (Current->getType() == types::TY_Nothing)
3135 break;
3136 }
3137
Samuel Antao64e965e2016-09-30 15:34:19 +00003138 // If we ended with something, add to the output list.
3139 if (Current)
Justin Lebar41094612016-01-11 23:07:27 +00003140 Actions.push_back(Current);
Samuel Antao64e965e2016-09-30 15:34:19 +00003141
3142 // Add any top level actions generated for offloading.
3143 OffloadBuilder.appendTopLevelActions(Actions, Current, InputArg);
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00003144 }
Daniel Dunbar65229332009-03-13 11:38:42 +00003145
Samuel Antao64e965e2016-09-30 15:34:19 +00003146 // Add a link action if necessary.
Samuel Antaod06239d2016-07-15 23:13:27 +00003147 if (!LinkerInputs.empty()) {
Samuel Antao64e965e2016-09-30 15:34:19 +00003148 Action *LA = C.MakeAction<LinkJobAction>(LinkerInputs, types::TY_Image);
3149 LA = OffloadBuilder.processHostLinkAction(LA);
3150 Actions.push_back(LA);
Samuel Antaod06239d2016-07-15 23:13:27 +00003151 }
Daniel Dunbarc7a67b72009-12-22 23:19:32 +00003152
3153 // If we are linking, claim any options which are obviously only used for
3154 // compilation.
Hans Wennborga8ef14f2013-09-17 00:03:41 +00003155 if (FinalPhase == phases::Link && PL.size() == 1) {
Daniel Dunbarc7a67b72009-12-22 23:19:32 +00003156 Args.ClaimAllArgs(options::OPT_CompileOnly_Group);
Hans Wennborga8ef14f2013-09-17 00:03:41 +00003157 Args.ClaimAllArgs(options::OPT_cl_compile_Group);
3158 }
3159
3160 // Claim ignored clang-cl options.
3161 Args.ClaimAllArgs(options::OPT_cl_ignored_Group);
Artem Belevichbaae0932015-07-28 21:01:30 +00003162
Justin Lebardc3c5042016-04-19 02:27:07 +00003163 // Claim --cuda-host-only and --cuda-compile-host-device, which may be passed
3164 // to non-CUDA compilations and should not trigger warnings there.
Artem Belevichbaae0932015-07-28 21:01:30 +00003165 Args.ClaimAllArgs(options::OPT_cuda_host_only);
Justin Lebardc3c5042016-04-19 02:27:07 +00003166 Args.ClaimAllArgs(options::OPT_cuda_compile_host_device);
Daniel Dunbar65229332009-03-13 11:38:42 +00003167}
3168
Artem Belevichecb178b2018-03-21 22:22:59 +00003169Action *Driver::ConstructPhaseAction(
3170 Compilation &C, const ArgList &Args, phases::ID Phase, Action *Input,
3171 Action::OffloadKind TargetDeviceOffloadKind) const {
Daniel Dunbar2608c542009-03-18 01:38:48 +00003172 llvm::PrettyStackTraceString CrashInfo("Constructing phase actions");
Samuel Antao64e965e2016-09-30 15:34:19 +00003173
3174 // Some types skip the assembler phase (e.g., llvm-bc), but we can't
3175 // encode this in the steps because the intermediate type depends on
3176 // arguments. Just special case here.
3177 if (Phase == phases::Assemble && Input->getType() != types::TY_PP_Asm)
3178 return Input;
3179
Daniel Dunbar65229332009-03-13 11:38:42 +00003180 // Build the appropriate action.
3181 switch (Phase) {
Douglas Katzmana67e50c2015-06-26 15:47:46 +00003182 case phases::Link:
3183 llvm_unreachable("link action invalid here.");
Daniel Dunbar65229332009-03-13 11:38:42 +00003184 case phases::Preprocess: {
Daniel Dunbard67a3222009-03-30 06:36:42 +00003185 types::ID OutputTy;
3186 // -{M, MM} alter the output type.
Daniel Dunbar86aed7d2010-12-08 21:33:40 +00003187 if (Args.hasArg(options::OPT_M, options::OPT_MM)) {
Daniel Dunbard67a3222009-03-30 06:36:42 +00003188 OutputTy = types::TY_Dependencies;
3189 } else {
David Blaikie5d577a22012-06-29 22:03:56 +00003190 OutputTy = Input->getType();
3191 if (!Args.hasFlag(options::OPT_frewrite_includes,
Justin Bognerce8245b2014-06-24 08:01:01 +00003192 options::OPT_fno_rewrite_includes, false) &&
Richard Smith86a3ef52017-06-09 21:24:02 +00003193 !Args.hasFlag(options::OPT_frewrite_imports,
3194 options::OPT_fno_rewrite_imports, false) &&
Justin Bognerce8245b2014-06-24 08:01:01 +00003195 !CCGenDiagnostics)
David Blaikie5d577a22012-06-29 22:03:56 +00003196 OutputTy = types::getPreprocessedType(OutputTy);
Daniel Dunbard67a3222009-03-30 06:36:42 +00003197 assert(OutputTy != types::TY_INVALID &&
3198 "Cannot preprocess this input type!");
3199 }
Justin Lebar41094612016-01-11 23:07:27 +00003200 return C.MakeAction<PreprocessJobAction>(Input, OutputTy);
Daniel Dunbar65229332009-03-13 11:38:42 +00003201 }
Aaron Ballman1f10cc52012-07-31 01:21:00 +00003202 case phases::Precompile: {
Richard Smithdd4ad3d2016-08-30 19:06:26 +00003203 types::ID OutputTy = getPrecompiledType(Input->getType());
3204 assert(OutputTy != types::TY_INVALID &&
3205 "Cannot precompile this input type!");
Aaron Ballman1f10cc52012-07-31 01:21:00 +00003206 if (Args.hasArg(options::OPT_fsyntax_only)) {
3207 // Syntax checks should not emit a PCH file
3208 OutputTy = types::TY_Nothing;
3209 }
Justin Lebar41094612016-01-11 23:07:27 +00003210 return C.MakeAction<PrecompileJobAction>(Input, OutputTy);
Aaron Ballman1f10cc52012-07-31 01:21:00 +00003211 }
Daniel Dunbar65229332009-03-13 11:38:42 +00003212 case phases::Compile: {
David Blaikie486f4402014-08-29 07:25:23 +00003213 if (Args.hasArg(options::OPT_fsyntax_only))
Justin Lebar41094612016-01-11 23:07:27 +00003214 return C.MakeAction<CompileJobAction>(Input, types::TY_Nothing);
David Blaikie486f4402014-08-29 07:25:23 +00003215 if (Args.hasArg(options::OPT_rewrite_objc))
Justin Lebar41094612016-01-11 23:07:27 +00003216 return C.MakeAction<CompileJobAction>(Input, types::TY_RewrittenObjC);
David Blaikie486f4402014-08-29 07:25:23 +00003217 if (Args.hasArg(options::OPT_rewrite_legacy_objc))
Justin Lebar41094612016-01-11 23:07:27 +00003218 return C.MakeAction<CompileJobAction>(Input,
3219 types::TY_RewrittenLegacyObjC);
David Blaikie486f4402014-08-29 07:25:23 +00003220 if (Args.hasArg(options::OPT__analyze, options::OPT__analyze_auto))
Justin Lebar41094612016-01-11 23:07:27 +00003221 return C.MakeAction<AnalyzeJobAction>(Input, types::TY_Plist);
David Blaikie486f4402014-08-29 07:25:23 +00003222 if (Args.hasArg(options::OPT__migrate))
Justin Lebar41094612016-01-11 23:07:27 +00003223 return C.MakeAction<MigrateJobAction>(Input, types::TY_Remap);
David Blaikie486f4402014-08-29 07:25:23 +00003224 if (Args.hasArg(options::OPT_emit_ast))
Justin Lebar41094612016-01-11 23:07:27 +00003225 return C.MakeAction<CompileJobAction>(Input, types::TY_AST);
David Blaikie486f4402014-08-29 07:25:23 +00003226 if (Args.hasArg(options::OPT_module_file_info))
Justin Lebar41094612016-01-11 23:07:27 +00003227 return C.MakeAction<CompileJobAction>(Input, types::TY_ModuleFile);
David Blaikie486f4402014-08-29 07:25:23 +00003228 if (Args.hasArg(options::OPT_verify_pch))
Justin Lebar41094612016-01-11 23:07:27 +00003229 return C.MakeAction<VerifyPCHJobAction>(Input, types::TY_Nothing);
3230 return C.MakeAction<CompileJobAction>(Input, types::TY_LLVM_BC);
Bob Wilson23a55f12014-12-21 07:00:00 +00003231 }
3232 case phases::Backend: {
Artem Belevichecb178b2018-03-21 22:22:59 +00003233 if (isUsingLTO() && TargetDeviceOffloadKind == Action::OFK_None) {
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00003234 types::ID Output =
Douglas Katzmana67e50c2015-06-26 15:47:46 +00003235 Args.hasArg(options::OPT_S) ? types::TY_LTO_IR : types::TY_LTO_BC;
Justin Lebar41094612016-01-11 23:07:27 +00003236 return C.MakeAction<BackendJobAction>(Input, Output);
David Blaikie486f4402014-08-29 07:25:23 +00003237 }
3238 if (Args.hasArg(options::OPT_emit_llvm)) {
Shuxin Yang4b3c7ff2013-08-23 21:34:57 +00003239 types::ID Output =
Douglas Katzmana67e50c2015-06-26 15:47:46 +00003240 Args.hasArg(options::OPT_S) ? types::TY_LLVM_IR : types::TY_LLVM_BC;
Justin Lebar41094612016-01-11 23:07:27 +00003241 return C.MakeAction<BackendJobAction>(Input, Output);
Daniel Dunbar65229332009-03-13 11:38:42 +00003242 }
Justin Lebar41094612016-01-11 23:07:27 +00003243 return C.MakeAction<BackendJobAction>(Input, types::TY_PP_Asm);
Daniel Dunbar65229332009-03-13 11:38:42 +00003244 }
3245 case phases::Assemble:
Justin Lebar21e5d4f2016-01-14 21:41:27 +00003246 return C.MakeAction<AssembleJobAction>(std::move(Input), types::TY_Object);
Daniel Dunbar65229332009-03-13 11:38:42 +00003247 }
3248
David Blaikie83d382b2011-09-23 05:06:16 +00003249 llvm_unreachable("invalid phase in ConstructPhaseAction");
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00003250}
3251
Daniel Dunbarf0eddb82009-03-18 02:55:38 +00003252void Driver::BuildJobs(Compilation &C) const {
Daniel Dunbar2608c542009-03-18 01:38:48 +00003253 llvm::PrettyStackTraceString CrashInfo("Building compilation jobs");
Daniel Dunbare75d8342009-03-16 06:56:51 +00003254
3255 Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o);
3256
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00003257 // It is an error to provide a -o option if we are making multiple output
3258 // files.
Daniel Dunbare75d8342009-03-16 06:56:51 +00003259 if (FinalOutput) {
3260 unsigned NumOutputs = 0;
Saleem Abdulrasoolda3f4e52014-12-29 21:02:47 +00003261 for (const Action *A : C.getActions())
3262 if (A->getType() != types::TY_Nothing)
Daniel Dunbare75d8342009-03-16 06:56:51 +00003263 ++NumOutputs;
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00003264
Daniel Dunbare75d8342009-03-16 06:56:51 +00003265 if (NumOutputs > 1) {
3266 Diag(clang::diag::err_drv_output_argument_with_multiple_files);
Craig Topper92fc2df2014-05-17 16:56:41 +00003267 FinalOutput = nullptr;
Daniel Dunbare75d8342009-03-16 06:56:51 +00003268 }
3269 }
3270
Chad Rosier35767232013-04-30 22:01:21 +00003271 // Collect the list of architectures.
3272 llvm::StringSet<> ArchNames;
Saleem Abdulrasool688b6bc2014-12-29 19:01:36 +00003273 if (C.getDefaultToolChain().getTriple().isOSBinFormatMachO())
3274 for (const Arg *A : C.getArgs())
Chad Rosier35767232013-04-30 22:01:21 +00003275 if (A->getOption().matches(options::OPT_arch))
3276 ArchNames.insert(A->getValue());
Chad Rosier35767232013-04-30 22:01:21 +00003277
Justin Lebarb44f6fe2016-01-14 21:41:21 +00003278 // Set of (Action, canonical ToolChain triple) pairs we've built jobs for.
3279 std::map<std::pair<const Action *, std::string>, InputInfo> CachedResults;
Saleem Abdulrasool688b6bc2014-12-29 19:01:36 +00003280 for (Action *A : C.getActions()) {
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00003281 // If we are linking an image for multiple archs then the linker wants
3282 // -arch_multiple and -final_output <final image name>. Unfortunately, this
3283 // doesn't fit in cleanly because we have to pass this information down.
Daniel Dunbare75d8342009-03-16 06:56:51 +00003284 //
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00003285 // FIXME: This is a hack; find a cleaner way to integrate this into the
3286 // process.
Craig Topper92fc2df2014-05-17 16:56:41 +00003287 const char *LinkingOutput = nullptr;
Daniel Dunbardd765242009-03-26 16:12:09 +00003288 if (isa<LipoJobAction>(A)) {
Daniel Dunbare75d8342009-03-16 06:56:51 +00003289 if (FinalOutput)
Richard Smithbd55daf2012-11-01 04:30:05 +00003290 LinkingOutput = FinalOutput->getValue();
Daniel Dunbare75d8342009-03-16 06:56:51 +00003291 else
Hans Wennborga7707222015-01-09 17:38:53 +00003292 LinkingOutput = getDefaultImageName();
Daniel Dunbare75d8342009-03-16 06:56:51 +00003293 }
3294
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00003295 BuildJobsForAction(C, A, &C.getDefaultToolChain(),
Mehdi Aminic50b1a22016-10-07 21:27:26 +00003296 /*BoundArch*/ StringRef(),
Daniel Dunbare75d8342009-03-16 06:56:51 +00003297 /*AtTopLevel*/ true,
Chad Rosier35767232013-04-30 22:01:21 +00003298 /*MultipleArchs*/ ArchNames.size() > 1,
Samuel Antaod06239d2016-07-15 23:13:27 +00003299 /*LinkingOutput*/ LinkingOutput, CachedResults,
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003300 /*TargetDeviceOffloadKind*/ Action::OFK_None);
Daniel Dunbare75d8342009-03-16 06:56:51 +00003301 }
Daniel Dunbar3ce436d2009-03-16 06:42:30 +00003302
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00003303 // If the user passed -Qunused-arguments or there were errors, don't warn
3304 // about any unused arguments.
Argyrios Kyrtzidis31448a42010-11-18 21:47:07 +00003305 if (Diags.hasErrorOccurred() ||
Daniel Dunbara3cfbe32009-04-07 19:04:18 +00003306 C.getArgs().hasArg(options::OPT_Qunused_arguments))
Daniel Dunbard175d972009-03-18 18:03:46 +00003307 return;
3308
Daniel Dunbar58399ae2009-03-29 22:24:54 +00003309 // Claim -### here.
Douglas Katzmana67e50c2015-06-26 15:47:46 +00003310 (void)C.getArgs().hasArg(options::OPT__HASH_HASH_HASH);
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00003311
Nico Weber47bf5052016-04-25 21:15:49 +00003312 // Claim --driver-mode, --rsp-quoting, it was handled earlier.
Douglas Katzmana67e50c2015-06-26 15:47:46 +00003313 (void)C.getArgs().hasArg(options::OPT_driver_mode);
Nico Weber47bf5052016-04-25 21:15:49 +00003314 (void)C.getArgs().hasArg(options::OPT_rsp_quoting);
Hans Wennborg70850d82013-07-18 20:29:38 +00003315
Saleem Abdulrasool688b6bc2014-12-29 19:01:36 +00003316 for (Arg *A : C.getArgs()) {
Daniel Dunbar3ce436d2009-03-16 06:42:30 +00003317 // FIXME: It would be nice to be able to send the argument to the
David Blaikie9c902b52011-09-25 23:23:43 +00003318 // DiagnosticsEngine, so that extra values, position, and so on could be
3319 // printed.
Daniel Dunbar90dd6f42009-04-04 00:52:26 +00003320 if (!A->isClaimed()) {
Michael J. Spencer66e2b202012-10-19 22:37:06 +00003321 if (A->getOption().hasFlag(options::NoArgumentUnused))
Daniel Dunbara3cfbe32009-04-07 19:04:18 +00003322 continue;
3323
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00003324 // Suppress the warning automatically if this is just a flag, and it is an
3325 // instance of an argument we already claimed.
Daniel Dunbar90dd6f42009-04-04 00:52:26 +00003326 const Option &Opt = A->getOption();
Michael J. Spencerad3ccc32012-08-20 21:41:17 +00003327 if (Opt.getKind() == Option::FlagClass) {
Daniel Dunbar90dd6f42009-04-04 00:52:26 +00003328 bool DuplicateClaimed = false;
3329
Sean Silva14facf32015-06-09 01:57:17 +00003330 for (const Arg *AA : C.getArgs().filtered(&Opt)) {
3331 if (AA->isClaimed()) {
Daniel Dunbar90dd6f42009-04-04 00:52:26 +00003332 DuplicateClaimed = true;
3333 break;
3334 }
3335 }
3336
3337 if (DuplicateClaimed)
3338 continue;
3339 }
3340
Ehsan Akhgarid8518332016-01-25 21:14:52 +00003341 // In clang-cl, don't mention unknown arguments here since they have
3342 // already been warned about.
3343 if (!IsCLMode() || !A->getOption().matches(options::OPT_UNKNOWN))
3344 Diag(clang::diag::warn_drv_unused_argument)
3345 << A->getAsString(C.getArgs());
Daniel Dunbar90dd6f42009-04-04 00:52:26 +00003346 }
Daniel Dunbar3ce436d2009-03-16 06:42:30 +00003347 }
Daniel Dunbar95e6b192009-03-13 22:12:33 +00003348}
Daniel Dunbarc4343942010-02-03 03:07:56 +00003349
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00003350namespace {
3351/// Utility class to control the collapse of dependent actions and select the
3352/// tools accordingly.
3353class ToolSelector final {
3354 /// The tool chain this selector refers to.
3355 const ToolChain &TC;
Daniel Dunbarf9ff3502010-05-14 02:03:00 +00003356
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00003357 /// The compilation this selector refers to.
3358 const Compilation &C;
Samuel Antaod06239d2016-07-15 23:13:27 +00003359
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00003360 /// The base action this selector refers to.
3361 const JobAction *BaseAction;
Samuel Antaod06239d2016-07-15 23:13:27 +00003362
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00003363 /// Set to true if the current toolchain refers to host actions.
3364 bool IsHostSelector;
Samuel Antaod06239d2016-07-15 23:13:27 +00003365
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00003366 /// Set to true if save-temps and embed-bitcode functionalities are active.
3367 bool SaveTemps;
3368 bool EmbedBitcode;
3369
3370 /// Get previous dependent action or null if that does not exist. If
3371 /// \a CanBeCollapsed is false, that action must be legal to collapse or
3372 /// null will be returned.
3373 const JobAction *getPrevDependentAction(const ActionList &Inputs,
3374 ActionList &SavedOffloadAction,
3375 bool CanBeCollapsed = true) {
3376 // An option can be collapsed only if it has a single input.
3377 if (Inputs.size() != 1)
Craig Topper92fc2df2014-05-17 16:56:41 +00003378 return nullptr;
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00003379
3380 Action *CurAction = *Inputs.begin();
3381 if (CanBeCollapsed &&
3382 !CurAction->isCollapsingWithNextDependentActionLegal())
3383 return nullptr;
3384
3385 // If the input action is an offload action. Look through it and save any
3386 // offload action that can be dropped in the event of a collapse.
3387 if (auto *OA = dyn_cast<OffloadAction>(CurAction)) {
3388 // If the dependent action is a device action, we will attempt to collapse
3389 // only with other device actions. Otherwise, we would do the same but
3390 // with host actions only.
3391 if (!IsHostSelector) {
3392 if (OA->hasSingleDeviceDependence(/*DoNotConsiderHostActions=*/true)) {
3393 CurAction =
3394 OA->getSingleDeviceDependence(/*DoNotConsiderHostActions=*/true);
3395 if (CanBeCollapsed &&
3396 !CurAction->isCollapsingWithNextDependentActionLegal())
3397 return nullptr;
3398 SavedOffloadAction.push_back(OA);
3399 return dyn_cast<JobAction>(CurAction);
3400 }
3401 } else if (OA->hasHostDependence()) {
3402 CurAction = OA->getHostDependence();
3403 if (CanBeCollapsed &&
3404 !CurAction->isCollapsingWithNextDependentActionLegal())
3405 return nullptr;
3406 SavedOffloadAction.push_back(OA);
3407 return dyn_cast<JobAction>(CurAction);
3408 }
3409 return nullptr;
3410 }
3411
3412 return dyn_cast<JobAction>(CurAction);
3413 }
3414
3415 /// Return true if an assemble action can be collapsed.
3416 bool canCollapseAssembleAction() const {
3417 return TC.useIntegratedAs() && !SaveTemps &&
3418 !C.getArgs().hasArg(options::OPT_via_file_asm) &&
3419 !C.getArgs().hasArg(options::OPT__SLASH_FA) &&
3420 !C.getArgs().hasArg(options::OPT__SLASH_Fa);
3421 }
3422
3423 /// Return true if a preprocessor action can be collapsed.
3424 bool canCollapsePreprocessorAction() const {
3425 return !C.getArgs().hasArg(options::OPT_no_integrated_cpp) &&
3426 !C.getArgs().hasArg(options::OPT_traditional_cpp) && !SaveTemps &&
3427 !C.getArgs().hasArg(options::OPT_rewrite_objc);
3428 }
3429
3430 /// Struct that relates an action with the offload actions that would be
3431 /// collapsed with it.
3432 struct JobActionInfo final {
3433 /// The action this info refers to.
3434 const JobAction *JA = nullptr;
3435 /// The offload actions we need to take care off if this action is
3436 /// collapsed.
3437 ActionList SavedOffloadAction;
3438 };
3439
3440 /// Append collapsed offload actions from the give nnumber of elements in the
3441 /// action info array.
3442 static void AppendCollapsedOffloadAction(ActionList &CollapsedOffloadAction,
3443 ArrayRef<JobActionInfo> &ActionInfo,
3444 unsigned ElementNum) {
3445 assert(ElementNum <= ActionInfo.size() && "Invalid number of elements.");
3446 for (unsigned I = 0; I < ElementNum; ++I)
3447 CollapsedOffloadAction.append(ActionInfo[I].SavedOffloadAction.begin(),
3448 ActionInfo[I].SavedOffloadAction.end());
3449 }
3450
3451 /// Functions that attempt to perform the combining. They detect if that is
3452 /// legal, and if so they update the inputs \a Inputs and the offload action
3453 /// that were collapsed in \a CollapsedOffloadAction. A tool that deals with
3454 /// the combined action is returned. If the combining is not legal or if the
3455 /// tool does not exist, null is returned.
3456 /// Currently three kinds of collapsing are supported:
3457 /// - Assemble + Backend + Compile;
3458 /// - Assemble + Backend ;
3459 /// - Backend + Compile.
3460 const Tool *
3461 combineAssembleBackendCompile(ArrayRef<JobActionInfo> ActionInfo,
3462 const ActionList *&Inputs,
3463 ActionList &CollapsedOffloadAction) {
3464 if (ActionInfo.size() < 3 || !canCollapseAssembleAction())
3465 return nullptr;
3466 auto *AJ = dyn_cast<AssembleJobAction>(ActionInfo[0].JA);
3467 auto *BJ = dyn_cast<BackendJobAction>(ActionInfo[1].JA);
3468 auto *CJ = dyn_cast<CompileJobAction>(ActionInfo[2].JA);
3469 if (!AJ || !BJ || !CJ)
3470 return nullptr;
3471
3472 // Get compiler tool.
3473 const Tool *T = TC.SelectTool(*CJ);
3474 if (!T)
3475 return nullptr;
3476
Steven Wu574b0f22016-03-01 01:07:58 +00003477 // When using -fembed-bitcode, it is required to have the same tool (clang)
3478 // for both CompilerJA and BackendJA. Otherwise, combine two stages.
3479 if (EmbedBitcode) {
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00003480 const Tool *BT = TC.SelectTool(*BJ);
3481 if (BT == T)
3482 return nullptr;
Steven Wu574b0f22016-03-01 01:07:58 +00003483 }
Bob Wilson23a55f12014-12-21 07:00:00 +00003484
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00003485 if (!T->hasIntegratedAssembler())
Bob Wilson23a55f12014-12-21 07:00:00 +00003486 return nullptr;
Samuel Antaod06239d2016-07-15 23:13:27 +00003487
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00003488 Inputs = &CJ->getInputs();
3489 AppendCollapsedOffloadAction(CollapsedOffloadAction, ActionInfo,
3490 /*NumElements=*/3);
3491 return T;
3492 }
3493 const Tool *combineAssembleBackend(ArrayRef<JobActionInfo> ActionInfo,
3494 const ActionList *&Inputs,
3495 ActionList &CollapsedOffloadAction) {
3496 if (ActionInfo.size() < 2 || !canCollapseAssembleAction())
3497 return nullptr;
3498 auto *AJ = dyn_cast<AssembleJobAction>(ActionInfo[0].JA);
3499 auto *BJ = dyn_cast<BackendJobAction>(ActionInfo[1].JA);
3500 if (!AJ || !BJ)
3501 return nullptr;
3502
3503 // Retrieve the compile job, backend action must always be preceded by one.
3504 ActionList CompileJobOffloadActions;
3505 auto *CJ = getPrevDependentAction(BJ->getInputs(), CompileJobOffloadActions,
3506 /*CanBeCollapsed=*/false);
3507 if (!AJ || !BJ || !CJ)
3508 return nullptr;
3509
3510 assert(isa<CompileJobAction>(CJ) &&
3511 "Expecting compile job preceding backend job.");
3512
3513 // Get compiler tool.
3514 const Tool *T = TC.SelectTool(*CJ);
3515 if (!T)
3516 return nullptr;
3517
3518 if (!T->hasIntegratedAssembler())
3519 return nullptr;
3520
3521 Inputs = &BJ->getInputs();
3522 AppendCollapsedOffloadAction(CollapsedOffloadAction, ActionInfo,
3523 /*NumElements=*/2);
3524 return T;
3525 }
3526 const Tool *combineBackendCompile(ArrayRef<JobActionInfo> ActionInfo,
3527 const ActionList *&Inputs,
3528 ActionList &CollapsedOffloadAction) {
Teresa Johnson9e4321c2018-04-17 16:39:25 +00003529 if (ActionInfo.size() < 2)
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00003530 return nullptr;
3531 auto *BJ = dyn_cast<BackendJobAction>(ActionInfo[0].JA);
3532 auto *CJ = dyn_cast<CompileJobAction>(ActionInfo[1].JA);
3533 if (!BJ || !CJ)
3534 return nullptr;
3535
Teresa Johnson9e4321c2018-04-17 16:39:25 +00003536 // Check if the initial input (to the compile job or its predessor if one
3537 // exists) is LLVM bitcode. In that case, no preprocessor step is required
3538 // and we can still collapse the compile and backend jobs when we have
3539 // -save-temps. I.e. there is no need for a separate compile job just to
3540 // emit unoptimized bitcode.
3541 bool InputIsBitcode = true;
3542 for (size_t i = 1; i < ActionInfo.size(); i++)
3543 if (ActionInfo[i].JA->getType() != types::TY_LLVM_BC &&
3544 ActionInfo[i].JA->getType() != types::TY_LTO_BC) {
3545 InputIsBitcode = false;
3546 break;
3547 }
3548 if (!InputIsBitcode && !canCollapsePreprocessorAction())
3549 return nullptr;
3550
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00003551 // Get compiler tool.
3552 const Tool *T = TC.SelectTool(*CJ);
3553 if (!T)
3554 return nullptr;
3555
Teresa Johnson9e4321c2018-04-17 16:39:25 +00003556 if (T->canEmitIR() && ((SaveTemps && !InputIsBitcode) || EmbedBitcode))
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00003557 return nullptr;
3558
3559 Inputs = &CJ->getInputs();
3560 AppendCollapsedOffloadAction(CollapsedOffloadAction, ActionInfo,
3561 /*NumElements=*/2);
3562 return T;
3563 }
3564
3565 /// Updates the inputs if the obtained tool supports combining with
3566 /// preprocessor action, and the current input is indeed a preprocessor
3567 /// action. If combining results in the collapse of offloading actions, those
3568 /// are appended to \a CollapsedOffloadAction.
3569 void combineWithPreprocessor(const Tool *T, const ActionList *&Inputs,
3570 ActionList &CollapsedOffloadAction) {
3571 if (!T || !canCollapsePreprocessorAction() || !T->hasIntegratedCPP())
3572 return;
3573
3574 // Attempt to get a preprocessor action dependence.
3575 ActionList PreprocessJobOffloadActions;
3576 auto *PJ = getPrevDependentAction(*Inputs, PreprocessJobOffloadActions);
3577 if (!PJ || !isa<PreprocessJobAction>(PJ))
3578 return;
3579
3580 // This is legal to combine. Append any offload action we found and set the
3581 // current inputs to preprocessor inputs.
3582 CollapsedOffloadAction.append(PreprocessJobOffloadActions.begin(),
3583 PreprocessJobOffloadActions.end());
3584 Inputs = &PJ->getInputs();
3585 }
3586
3587public:
3588 ToolSelector(const JobAction *BaseAction, const ToolChain &TC,
3589 const Compilation &C, bool SaveTemps, bool EmbedBitcode)
3590 : TC(TC), C(C), BaseAction(BaseAction), SaveTemps(SaveTemps),
3591 EmbedBitcode(EmbedBitcode) {
3592 assert(BaseAction && "Invalid base action.");
3593 IsHostSelector = BaseAction->getOffloadingDeviceKind() == Action::OFK_None;
3594 }
3595
3596 /// Check if a chain of actions can be combined and return the tool that can
3597 /// handle the combination of actions. The pointer to the current inputs \a
3598 /// Inputs and the list of offload actions \a CollapsedOffloadActions
3599 /// connected to collapsed actions are updated accordingly. The latter enables
3600 /// the caller of the selector to process them afterwards instead of just
3601 /// dropping them. If no suitable tool is found, null will be returned.
3602 const Tool *getTool(const ActionList *&Inputs,
3603 ActionList &CollapsedOffloadAction) {
3604 //
3605 // Get the largest chain of actions that we could combine.
3606 //
3607
3608 SmallVector<JobActionInfo, 5> ActionChain(1);
3609 ActionChain.back().JA = BaseAction;
3610 while (ActionChain.back().JA) {
3611 const Action *CurAction = ActionChain.back().JA;
3612
3613 // Grow the chain by one element.
3614 ActionChain.resize(ActionChain.size() + 1);
3615 JobActionInfo &AI = ActionChain.back();
3616
3617 // Attempt to fill it with the
3618 AI.JA =
3619 getPrevDependentAction(CurAction->getInputs(), AI.SavedOffloadAction);
Daniel Dunbarc4343942010-02-03 03:07:56 +00003620 }
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00003621
3622 // Pop the last action info as it could not be filled.
3623 ActionChain.pop_back();
3624
3625 //
3626 // Attempt to combine actions. If all combining attempts failed, just return
3627 // the tool of the provided action. At the end we attempt to combine the
3628 // action with any preprocessor action it may depend on.
3629 //
3630
3631 const Tool *T = combineAssembleBackendCompile(ActionChain, Inputs,
3632 CollapsedOffloadAction);
3633 if (!T)
3634 T = combineAssembleBackend(ActionChain, Inputs, CollapsedOffloadAction);
3635 if (!T)
3636 T = combineBackendCompile(ActionChain, Inputs, CollapsedOffloadAction);
3637 if (!T) {
3638 Inputs = &BaseAction->getInputs();
3639 T = TC.SelectTool(*BaseAction);
3640 }
3641
3642 combineWithPreprocessor(T, Inputs, CollapsedOffloadAction);
3643 return T;
Daniel Dunbarc4343942010-02-03 03:07:56 +00003644 }
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00003645};
Daniel Dunbarc4343942010-02-03 03:07:56 +00003646}
3647
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003648/// Return a string that uniquely identifies the result of a job. The bound arch
3649/// is not necessarily represented in the toolchain's triple -- for example,
3650/// armv7 and armv7s both map to the same triple -- so we need both in our map.
3651/// Also, we need to add the offloading device kind, as the same tool chain can
3652/// be used for host and device for some programming models, e.g. OpenMP.
3653static std::string GetTriplePlusArchString(const ToolChain *TC,
3654 StringRef BoundArch,
3655 Action::OffloadKind OffloadKind) {
Justin Lebar55c83322016-01-16 03:30:08 +00003656 std::string TriplePlusArch = TC->getTriple().normalize();
Mehdi Aminic50b1a22016-10-07 21:27:26 +00003657 if (!BoundArch.empty()) {
Justin Lebar55c83322016-01-16 03:30:08 +00003658 TriplePlusArch += "-";
3659 TriplePlusArch += BoundArch;
3660 }
Samuel Antao59efaed2016-10-27 17:31:22 +00003661 TriplePlusArch += "-";
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003662 TriplePlusArch += Action::GetOffloadKindName(OffloadKind);
3663 return TriplePlusArch;
3664}
3665
3666InputInfo Driver::BuildJobsForAction(
3667 Compilation &C, const Action *A, const ToolChain *TC, StringRef BoundArch,
3668 bool AtTopLevel, bool MultipleArchs, const char *LinkingOutput,
3669 std::map<std::pair<const Action *, std::string>, InputInfo> &CachedResults,
3670 Action::OffloadKind TargetDeviceOffloadKind) const {
3671 std::pair<const Action *, std::string> ActionTC = {
3672 A, GetTriplePlusArchString(TC, BoundArch, TargetDeviceOffloadKind)};
Justin Lebarb44f6fe2016-01-14 21:41:21 +00003673 auto CachedResult = CachedResults.find(ActionTC);
3674 if (CachedResult != CachedResults.end()) {
3675 return CachedResult->second;
3676 }
Samuel Antaod06239d2016-07-15 23:13:27 +00003677 InputInfo Result = BuildJobsForActionNoCache(
3678 C, A, TC, BoundArch, AtTopLevel, MultipleArchs, LinkingOutput,
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003679 CachedResults, TargetDeviceOffloadKind);
Justin Lebarb44f6fe2016-01-14 21:41:21 +00003680 CachedResults[ActionTC] = Result;
3681 return Result;
3682}
3683
3684InputInfo Driver::BuildJobsForActionNoCache(
Mehdi Aminic50b1a22016-10-07 21:27:26 +00003685 Compilation &C, const Action *A, const ToolChain *TC, StringRef BoundArch,
Justin Lebarb44f6fe2016-01-14 21:41:21 +00003686 bool AtTopLevel, bool MultipleArchs, const char *LinkingOutput,
Samuel Antaod06239d2016-07-15 23:13:27 +00003687 std::map<std::pair<const Action *, std::string>, InputInfo> &CachedResults,
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003688 Action::OffloadKind TargetDeviceOffloadKind) const {
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00003689 llvm::PrettyStackTraceString CrashInfo("Building compilation jobs");
Daniel Dunbarc4acf9d2009-03-18 23:18:19 +00003690
Samuel Antaod06239d2016-07-15 23:13:27 +00003691 InputInfoList OffloadDependencesInputInfo;
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003692 bool BuildingForOffloadDevice = TargetDeviceOffloadKind != Action::OFK_None;
Samuel Antaod06239d2016-07-15 23:13:27 +00003693 if (const OffloadAction *OA = dyn_cast<OffloadAction>(A)) {
Alex Lorenz4003a982017-08-08 11:22:21 +00003694 // The 'Darwin' toolchain is initialized only when its arguments are
3695 // computed. Get the default arguments for OFK_None to ensure that
3696 // initialization is performed before processing the offload action.
3697 // FIXME: Remove when darwin's toolchain is initialized during construction.
3698 C.getArgsForToolChain(TC, BoundArch, Action::OFK_None);
3699
Samuel Antaod06239d2016-07-15 23:13:27 +00003700 // The offload action is expected to be used in four different situations.
3701 //
3702 // a) Set a toolchain/architecture/kind for a host action:
3703 // Host Action 1 -> OffloadAction -> Host Action 2
3704 //
3705 // b) Set a toolchain/architecture/kind for a device action;
3706 // Device Action 1 -> OffloadAction -> Device Action 2
3707 //
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00003708 // c) Specify a device dependence to a host action;
Samuel Antaod06239d2016-07-15 23:13:27 +00003709 // Device Action 1 _
3710 // \
3711 // Host Action 1 ---> OffloadAction -> Host Action 2
3712 //
3713 // d) Specify a host dependence to a device action.
3714 // Host Action 1 _
3715 // \
3716 // Device Action 1 ---> OffloadAction -> Device Action 2
3717 //
3718 // For a) and b), we just return the job generated for the dependence. For
3719 // c) and d) we override the current action with the host/device dependence
3720 // if the current toolchain is host/device and set the offload dependences
3721 // info with the jobs obtained from the device/host dependence(s).
3722
3723 // If there is a single device option, just generate the job for it.
3724 if (OA->hasSingleDeviceDependence()) {
3725 InputInfo DevA;
3726 OA->doOnEachDeviceDependence([&](Action *DepA, const ToolChain *DepTC,
3727 const char *DepBoundArch) {
3728 DevA =
3729 BuildJobsForAction(C, DepA, DepTC, DepBoundArch, AtTopLevel,
3730 /*MultipleArchs*/ !!DepBoundArch, LinkingOutput,
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003731 CachedResults, DepA->getOffloadingDeviceKind());
Samuel Antaod06239d2016-07-15 23:13:27 +00003732 });
3733 return DevA;
Artem Belevich0ff05cd2015-07-13 23:27:56 +00003734 }
Samuel Antaod06239d2016-07-15 23:13:27 +00003735
3736 // If 'Action 2' is host, we generate jobs for the device dependences and
3737 // override the current action with the host dependence. Otherwise, we
3738 // generate the host dependences and override the action with the device
3739 // dependence. The dependences can't therefore be a top-level action.
3740 OA->doOnEachDependence(
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003741 /*IsHostDependence=*/BuildingForOffloadDevice,
Samuel Antaod06239d2016-07-15 23:13:27 +00003742 [&](Action *DepA, const ToolChain *DepTC, const char *DepBoundArch) {
3743 OffloadDependencesInputInfo.push_back(BuildJobsForAction(
3744 C, DepA, DepTC, DepBoundArch, /*AtTopLevel=*/false,
3745 /*MultipleArchs*/ !!DepBoundArch, LinkingOutput, CachedResults,
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003746 DepA->getOffloadingDeviceKind()));
Samuel Antaod06239d2016-07-15 23:13:27 +00003747 });
3748
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003749 A = BuildingForOffloadDevice
Samuel Antaod06239d2016-07-15 23:13:27 +00003750 ? OA->getSingleDeviceDependence(/*DoNotConsiderHostActions=*/true)
3751 : OA->getHostDependence();
Artem Belevich0ff05cd2015-07-13 23:27:56 +00003752 }
3753
Daniel Dunbare75d8342009-03-16 06:56:51 +00003754 if (const InputAction *IA = dyn_cast<InputAction>(A)) {
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00003755 // FIXME: It would be nice to not claim this here; maybe the old scheme of
3756 // just using Args was better?
Daniel Dunbar5cdf3e02009-03-19 07:29:38 +00003757 const Arg &Input = IA->getInputArg();
3758 Input.claim();
Daniel Dunbar35cbfeb2010-06-09 22:31:08 +00003759 if (Input.getOption().matches(options::OPT_INPUT)) {
Richard Smithbd55daf2012-11-01 04:30:05 +00003760 const char *Name = Input.getValue();
Justin Lebard98cea82016-01-11 23:15:21 +00003761 return InputInfo(A, Name, /* BaseInput = */ Name);
Douglas Katzman678d0cb2015-06-16 18:01:24 +00003762 }
Justin Lebard98cea82016-01-11 23:15:21 +00003763 return InputInfo(A, &Input, /* BaseInput = */ "");
Daniel Dunbare75d8342009-03-16 06:56:51 +00003764 }
3765
3766 if (const BindArchAction *BAA = dyn_cast<BindArchAction>(A)) {
Chad Rosiera78a6eb2012-04-27 16:50:38 +00003767 const ToolChain *TC;
Mehdi Aminic50b1a22016-10-07 21:27:26 +00003768 StringRef ArchName = BAA->getArchName();
Daniel Dunbar1ef3f2a2009-09-08 23:37:19 +00003769
Mehdi Aminic50b1a22016-10-07 21:27:26 +00003770 if (!ArchName.empty())
Andrey Turetskiy6a8b91d2016-04-21 10:16:48 +00003771 TC = &getToolChain(C.getArgs(),
Petr Hosekdd38d932018-05-29 22:35:39 +00003772 computeTargetTriple(*this, TargetTriple,
Andrey Turetskiy6a8b91d2016-04-21 10:16:48 +00003773 C.getArgs(), ArchName));
Chad Rosiera78a6eb2012-04-27 16:50:38 +00003774 else
3775 TC = &C.getDefaultToolChain();
Daniel Dunbar1ef3f2a2009-09-08 23:37:19 +00003776
Nico Weber5a459f82016-02-23 19:30:43 +00003777 return BuildJobsForAction(C, *BAA->input_begin(), TC, ArchName, AtTopLevel,
Samuel Antaod06239d2016-07-15 23:13:27 +00003778 MultipleArchs, LinkingOutput, CachedResults,
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003779 TargetDeviceOffloadKind);
Daniel Dunbare75d8342009-03-16 06:56:51 +00003780 }
3781
Artem Belevich0ff05cd2015-07-13 23:27:56 +00003782
Daniel Dunbare75d8342009-03-16 06:56:51 +00003783 const ActionList *Inputs = &A->getInputs();
Daniel Dunbarc4343942010-02-03 03:07:56 +00003784
3785 const JobAction *JA = cast<JobAction>(A);
Samuel Antaod06239d2016-07-15 23:13:27 +00003786 ActionList CollapsedOffloadActions;
3787
Mehdi Amini6683e222017-01-24 18:12:25 +00003788 ToolSelector TS(JA, *TC, C, isSaveTempsEnabled(),
3789 embedBitcodeInObject() && !isUsingLTO());
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00003790 const Tool *T = TS.getTool(Inputs, CollapsedOffloadActions);
3791
Rafael Espindola79764462013-03-24 15:06:53 +00003792 if (!T)
Justin Lebar9eaa4892016-01-11 23:09:32 +00003793 return InputInfo();
Daniel Dunbare75d8342009-03-16 06:56:51 +00003794
Samuel Antaod06239d2016-07-15 23:13:27 +00003795 // If we've collapsed action list that contained OffloadAction we
3796 // need to build jobs for host/device-side inputs it may have held.
3797 for (const auto *OA : CollapsedOffloadActions)
3798 cast<OffloadAction>(OA)->doOnEachDependence(
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003799 /*IsHostDependence=*/BuildingForOffloadDevice,
Samuel Antaod06239d2016-07-15 23:13:27 +00003800 [&](Action *DepA, const ToolChain *DepTC, const char *DepBoundArch) {
3801 OffloadDependencesInputInfo.push_back(BuildJobsForAction(
Artem Belevichbee2f412016-08-22 18:50:34 +00003802 C, DepA, DepTC, DepBoundArch, /* AtTopLevel */ false,
Samuel Antaod06239d2016-07-15 23:13:27 +00003803 /*MultipleArchs=*/!!DepBoundArch, LinkingOutput, CachedResults,
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003804 DepA->getOffloadingDeviceKind()));
Samuel Antaod06239d2016-07-15 23:13:27 +00003805 });
Artem Belevichf8144ab2015-08-27 18:10:41 +00003806
Daniel Dunbare75d8342009-03-16 06:56:51 +00003807 // Only use pipes when there is exactly one input.
Daniel Dunbar1a093d22009-03-18 06:00:36 +00003808 InputInfoList InputInfos;
Saleem Abdulrasoolda3f4e52014-12-29 21:02:47 +00003809 for (const Action *Input : *Inputs) {
Eric Christopher14668dd2013-02-18 00:38:25 +00003810 // Treat dsymutil and verify sub-jobs as being at the top-level too, they
3811 // shouldn't get temporary output names.
Daniel Dunbar6beaf512010-06-04 18:28:41 +00003812 // FIXME: Clean this up.
Justin Lebar9eaa4892016-01-11 23:09:32 +00003813 bool SubJobAtTopLevel =
3814 AtTopLevel && (isa<DsymutilJobAction>(A) || isa<VerifyJobAction>(A));
Samuel Antaod06239d2016-07-15 23:13:27 +00003815 InputInfos.push_back(BuildJobsForAction(
3816 C, Input, TC, BoundArch, SubJobAtTopLevel, MultipleArchs, LinkingOutput,
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003817 CachedResults, A->getOffloadingDeviceKind()));
Daniel Dunbare75d8342009-03-16 06:56:51 +00003818 }
3819
Daniel Dunbare75d8342009-03-16 06:56:51 +00003820 // Always use the first input as the base input.
3821 const char *BaseInput = InputInfos[0].getBaseInput();
Daniel Dunbar7a178a42009-03-17 17:53:55 +00003822
Daniel Dunbar6beaf512010-06-04 18:28:41 +00003823 // ... except dsymutil actions, which use their actual input as the base
3824 // input.
3825 if (JA->getType() == types::TY_dSYM)
3826 BaseInput = InputInfos[0].getFilename();
3827
Samuel Antaod06239d2016-07-15 23:13:27 +00003828 // Append outputs of offload device jobs to the input list
3829 if (!OffloadDependencesInputInfo.empty())
3830 InputInfos.append(OffloadDependencesInputInfo.begin(),
3831 OffloadDependencesInputInfo.end());
Artem Belevich0ff05cd2015-07-13 23:27:56 +00003832
Vedant Kumar18286cf2016-07-27 23:02:20 +00003833 // Set the effective triple of the toolchain for the duration of this job.
3834 llvm::Triple EffectiveTriple;
3835 const ToolChain &ToolTC = T->getToolChain();
Samuel Antao31fef982016-10-27 17:39:44 +00003836 const ArgList &Args =
3837 C.getArgsForToolChain(TC, BoundArch, A->getOffloadingDeviceKind());
Vedant Kumar18286cf2016-07-27 23:02:20 +00003838 if (InputInfos.size() != 1) {
3839 EffectiveTriple = llvm::Triple(ToolTC.ComputeEffectiveClangTriple(Args));
3840 } else {
3841 // Pass along the input type if it can be unambiguously determined.
3842 EffectiveTriple = llvm::Triple(
3843 ToolTC.ComputeEffectiveClangTriple(Args, InputInfos[0].getType()));
3844 }
3845 RegisterEffectiveTriple TripleRAII(ToolTC, EffectiveTriple);
3846
Daniel Dunbard00272f2010-08-02 02:38:15 +00003847 // Determine the place to write output to, if any.
Justin Lebar9eaa4892016-01-11 23:09:32 +00003848 InputInfo Result;
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003849 InputInfoList UnbundlingResults;
3850 if (auto *UA = dyn_cast<OffloadUnbundlingJobAction>(JA)) {
3851 // If we have an unbundling job, we need to create results for all the
3852 // outputs. We also update the results cache so that other actions using
3853 // this unbundling action can get the right results.
3854 for (auto &UI : UA->getDependentActionsInfo()) {
3855 assert(UI.DependentOffloadKind != Action::OFK_None &&
3856 "Unbundling with no offloading??");
3857
3858 // Unbundling actions are never at the top level. When we generate the
3859 // offloading prefix, we also do that for the host file because the
3860 // unbundling action does not change the type of the output which can
3861 // cause a overwrite.
3862 std::string OffloadingPrefix = Action::GetOffloadingFileNamePrefix(
3863 UI.DependentOffloadKind,
3864 UI.DependentToolChain->getTriple().normalize(),
3865 /*CreatePrefixForHost=*/true);
3866 auto CurI = InputInfo(
Yaxun Liu609f7522018-05-11 19:02:18 +00003867 UA,
3868 GetNamedOutputPath(C, *UA, BaseInput, UI.DependentBoundArch,
3869 /*AtTopLevel=*/false,
3870 MultipleArchs ||
3871 UI.DependentOffloadKind == Action::OFK_HIP,
3872 OffloadingPrefix),
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003873 BaseInput);
3874 // Save the unbundling result.
3875 UnbundlingResults.push_back(CurI);
3876
3877 // Get the unique string identifier for this dependence and cache the
3878 // result.
3879 CachedResults[{A, GetTriplePlusArchString(
Gheorghe-Teodor Bercea52898432017-08-09 01:02:19 +00003880 UI.DependentToolChain, BoundArch,
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003881 UI.DependentOffloadKind)}] = CurI;
3882 }
3883
3884 // Now that we have all the results generated, select the one that should be
3885 // returned for the current depending action.
3886 std::pair<const Action *, std::string> ActionTC = {
3887 A, GetTriplePlusArchString(TC, BoundArch, TargetDeviceOffloadKind)};
3888 assert(CachedResults.find(ActionTC) != CachedResults.end() &&
3889 "Result does not exist??");
3890 Result = CachedResults[ActionTC];
3891 } else if (JA->getType() == types::TY_Nothing)
Justin Lebard98cea82016-01-11 23:15:21 +00003892 Result = InputInfo(A, BaseInput);
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003893 else {
3894 // We only have to generate a prefix for the host if this is not a top-level
3895 // action.
3896 std::string OffloadingPrefix = Action::GetOffloadingFileNamePrefix(
3897 A->getOffloadingDeviceKind(), TC->getTriple().normalize(),
3898 /*CreatePrefixForHost=*/!!A->getOffloadingHostActiveKinds() &&
3899 !AtTopLevel);
Justin Lebard98cea82016-01-11 23:15:21 +00003900 Result = InputInfo(A, GetNamedOutputPath(C, *JA, BaseInput, BoundArch,
Samuel Antaod06239d2016-07-15 23:13:27 +00003901 AtTopLevel, MultipleArchs,
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003902 OffloadingPrefix),
Justin Lebard98cea82016-01-11 23:15:21 +00003903 BaseInput);
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003904 }
Daniel Dunbar7a178a42009-03-17 17:53:55 +00003905
Chad Rosierbe10f982011-08-02 17:58:04 +00003906 if (CCCPrintBindings && !CCGenDiagnostics) {
Rafael Espindola79764462013-03-24 15:06:53 +00003907 llvm::errs() << "# \"" << T->getToolChain().getTripleString() << '"'
3908 << " - \"" << T->getName() << "\", inputs: [";
Daniel Dunbarb39cc522009-03-17 22:47:06 +00003909 for (unsigned i = 0, e = InputInfos.size(); i != e; ++i) {
3910 llvm::errs() << InputInfos[i].getAsString();
3911 if (i + 1 != e)
3912 llvm::errs() << ", ";
3913 }
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003914 if (UnbundlingResults.empty())
3915 llvm::errs() << "], output: " << Result.getAsString() << "\n";
3916 else {
3917 llvm::errs() << "], outputs: [";
3918 for (unsigned i = 0, e = UnbundlingResults.size(); i != e; ++i) {
3919 llvm::errs() << UnbundlingResults[i].getAsString();
3920 if (i + 1 != e)
3921 llvm::errs() << ", ";
3922 }
3923 llvm::errs() << "] \n";
3924 }
Daniel Dunbarb39cc522009-03-17 22:47:06 +00003925 } else {
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003926 if (UnbundlingResults.empty())
3927 T->ConstructJob(
3928 C, *JA, Result, InputInfos,
3929 C.getArgsForToolChain(TC, BoundArch, JA->getOffloadingDeviceKind()),
3930 LinkingOutput);
3931 else
Samuel Antao7108bf32016-11-03 15:41:50 +00003932 T->ConstructJobMultipleOutputs(
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003933 C, *JA, UnbundlingResults, InputInfos,
3934 C.getArgsForToolChain(TC, BoundArch, JA->getOffloadingDeviceKind()),
3935 LinkingOutput);
Daniel Dunbarb39cc522009-03-17 22:47:06 +00003936 }
Justin Lebar9eaa4892016-01-11 23:09:32 +00003937 return Result;
Daniel Dunbare75d8342009-03-16 06:56:51 +00003938}
3939
Hans Wennborga7707222015-01-09 17:38:53 +00003940const char *Driver::getDefaultImageName() const {
Petr Hosekdd38d932018-05-29 22:35:39 +00003941 llvm::Triple Target(llvm::Triple::normalize(TargetTriple));
Hans Wennborga7707222015-01-09 17:38:53 +00003942 return Target.isOSWindows() ? "a.exe" : "a.out";
3943}
3944
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003945/// Create output filename based on ArgValue, which could either be a
Hans Wennborg2c21f742013-10-17 16:16:23 +00003946/// full filename, filename without extension, or a directory. If ArgValue
3947/// does not provide a filename, then use BaseName, and use the extension
3948/// suitable for FileType.
Hans Wennborg207fcf02013-08-12 21:56:42 +00003949static const char *MakeCLOutputFilename(const ArgList &Args, StringRef ArgValue,
Douglas Katzmana67e50c2015-06-26 15:47:46 +00003950 StringRef BaseName,
3951 types::ID FileType) {
Hans Wennborg207fcf02013-08-12 21:56:42 +00003952 SmallString<128> Filename = ArgValue;
Justin Bogner5aaf2e72014-06-26 20:59:36 +00003953
Hans Wennborgf1a74252013-09-10 20:18:04 +00003954 if (ArgValue.empty()) {
3955 // If the argument is empty, output to BaseName in the current dir.
3956 Filename = BaseName;
3957 } else if (llvm::sys::path::is_separator(Filename.back())) {
Hans Wennborg207fcf02013-08-12 21:56:42 +00003958 // If the argument is a directory, output to BaseName in that dir.
3959 llvm::sys::path::append(Filename, BaseName);
3960 }
3961
3962 if (!llvm::sys::path::has_extension(ArgValue)) {
3963 // If the argument didn't provide an extension, then set it.
3964 const char *Extension = types::getTypeTempSuffix(FileType, true);
Hans Wennborgf1a74252013-09-10 20:18:04 +00003965
3966 if (FileType == types::TY_Image &&
3967 Args.hasArg(options::OPT__SLASH_LD, options::OPT__SLASH_LDd)) {
3968 // The output file is a dll.
3969 Extension = "dll";
3970 }
3971
Hans Wennborg207fcf02013-08-12 21:56:42 +00003972 llvm::sys::path::replace_extension(Filename, Extension);
3973 }
3974
3975 return Args.MakeArgString(Filename.c_str());
3976}
3977
Douglas Katzmana67e50c2015-06-26 15:47:46 +00003978const char *Driver::GetNamedOutputPath(Compilation &C, const JobAction &JA,
Daniel Dunbar7a178a42009-03-17 17:53:55 +00003979 const char *BaseInput,
Mehdi Aminic50b1a22016-10-07 21:27:26 +00003980 StringRef BoundArch, bool AtTopLevel,
Samuel Antaod06239d2016-07-15 23:13:27 +00003981 bool MultipleArchs,
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003982 StringRef OffloadingPrefix) const {
Daniel Dunbar2608c542009-03-18 01:38:48 +00003983 llvm::PrettyStackTraceString CrashInfo("Computing output path");
Daniel Dunbar7a178a42009-03-17 17:53:55 +00003984 // Output to a user requested destination?
Douglas Katzmana67e50c2015-06-26 15:47:46 +00003985 if (AtTopLevel && !isa<DsymutilJobAction>(JA) && !isa<VerifyJobAction>(JA)) {
Daniel Dunbar7a178a42009-03-17 17:53:55 +00003986 if (Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o))
Chad Rosier633dcdc2013-01-24 19:14:47 +00003987 return C.addResultFile(FinalOutput->getValue(), &JA);
Daniel Dunbar7a178a42009-03-17 17:53:55 +00003988 }
3989
Hans Wennborge0053472013-12-20 18:40:46 +00003990 // For /P, preprocess to file named after BaseInput.
3991 if (C.getArgs().hasArg(options::OPT__SLASH_P)) {
3992 assert(AtTopLevel && isa<PreprocessJobAction>(JA));
3993 StringRef BaseName = llvm::sys::path::filename(BaseInput);
Hans Wennborg04c764f2014-06-17 00:19:12 +00003994 StringRef NameArg;
Greg Bedwell065f70a2015-06-09 10:24:06 +00003995 if (Arg *A = C.getArgs().getLastArg(options::OPT__SLASH_Fi))
Hans Wennborg04c764f2014-06-17 00:19:12 +00003996 NameArg = A->getValue();
Douglas Katzmana67e50c2015-06-26 15:47:46 +00003997 return C.addResultFile(
3998 MakeCLOutputFilename(C.getArgs(), NameArg, BaseName, types::TY_PP_C),
3999 &JA);
Hans Wennborge0053472013-12-20 18:40:46 +00004000 }
4001
Nick Lewycky6e1ce292010-09-24 00:46:53 +00004002 // Default to writing to stdout?
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +00004003 if (AtTopLevel && !CCGenDiagnostics &&
4004 (isa<PreprocessJobAction>(JA) || JA.getType() == types::TY_ModuleFile))
Nick Lewycky6e1ce292010-09-24 00:46:53 +00004005 return "-";
4006
Hans Wennborg2c21f742013-10-17 16:16:23 +00004007 // Is this the assembly listing for /FA?
4008 if (JA.getType() == types::TY_PP_Asm &&
4009 (C.getArgs().hasArg(options::OPT__SLASH_FA) ||
4010 C.getArgs().hasArg(options::OPT__SLASH_Fa))) {
4011 // Use /Fa and the input filename to determine the asm file name.
4012 StringRef BaseName = llvm::sys::path::filename(BaseInput);
4013 StringRef FaValue = C.getArgs().getLastArgValue(options::OPT__SLASH_Fa);
Douglas Katzmana67e50c2015-06-26 15:47:46 +00004014 return C.addResultFile(
4015 MakeCLOutputFilename(C.getArgs(), FaValue, BaseName, JA.getType()),
4016 &JA);
Hans Wennborg2c21f742013-10-17 16:16:23 +00004017 }
4018
Daniel Dunbar7a178a42009-03-17 17:53:55 +00004019 // Output to a temporary file?
Reid Kleckner68eb60b2015-02-02 22:41:48 +00004020 if ((!AtTopLevel && !isSaveTempsEnabled() &&
Douglas Katzmana67e50c2015-06-26 15:47:46 +00004021 !C.getArgs().hasArg(options::OPT__SLASH_Fo)) ||
Chad Rosierbe10f982011-08-02 17:58:04 +00004022 CCGenDiagnostics) {
Chad Rosier97c37372011-08-26 22:27:02 +00004023 StringRef Name = llvm::sys::path::filename(BaseInput);
4024 std::pair<StringRef, StringRef> Split = Name.split('.');
Douglas Katzmana67e50c2015-06-26 15:47:46 +00004025 std::string TmpName = GetTemporaryPath(
4026 Split.first, types::getTypeTempSuffix(JA.getType(), IsCLMode()));
Malcolm Parsonsf76f6502016-11-02 10:39:27 +00004027 return C.addTempFile(C.getArgs().MakeArgString(TmpName));
Daniel Dunbar7a178a42009-03-17 17:53:55 +00004028 }
4029
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00004030 SmallString<128> BasePath(BaseInput);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004031 StringRef BaseName;
Daniel Dunbar67fea712011-03-25 18:16:51 +00004032
4033 // Dsymutil actions should use the full path.
Eric Christopher551ef452011-08-23 17:56:55 +00004034 if (isa<DsymutilJobAction>(JA) || isa<VerifyJobAction>(JA))
Daniel Dunbar67fea712011-03-25 18:16:51 +00004035 BaseName = BasePath;
4036 else
4037 BaseName = llvm::sys::path::filename(BasePath);
Daniel Dunbar7a178a42009-03-17 17:53:55 +00004038
4039 // Determine what the derived output name should be.
4040 const char *NamedOutput;
Hans Wennborg2b89a262013-08-06 22:11:28 +00004041
Hans Wennborg625fba82016-10-04 21:01:04 +00004042 if ((JA.getType() == types::TY_Object || JA.getType() == types::TY_LTO_BC) &&
Ehsan Akhgari81f36b72014-09-11 18:16:21 +00004043 C.getArgs().hasArg(options::OPT__SLASH_Fo, options::OPT__SLASH_o)) {
4044 // The /Fo or /o flag decides the object filename.
Douglas Katzmana67e50c2015-06-26 15:47:46 +00004045 StringRef Val =
4046 C.getArgs()
4047 .getLastArg(options::OPT__SLASH_Fo, options::OPT__SLASH_o)
4048 ->getValue();
4049 NamedOutput =
4050 MakeCLOutputFilename(C.getArgs(), Val, BaseName, types::TY_Object);
Hans Wennborg207fcf02013-08-12 21:56:42 +00004051 } else if (JA.getType() == types::TY_Image &&
Douglas Katzmana67e50c2015-06-26 15:47:46 +00004052 C.getArgs().hasArg(options::OPT__SLASH_Fe,
4053 options::OPT__SLASH_o)) {
Ehsan Akhgari81f36b72014-09-11 18:16:21 +00004054 // The /Fe or /o flag names the linked file.
Douglas Katzmana67e50c2015-06-26 15:47:46 +00004055 StringRef Val =
4056 C.getArgs()
4057 .getLastArg(options::OPT__SLASH_Fe, options::OPT__SLASH_o)
4058 ->getValue();
4059 NamedOutput =
4060 MakeCLOutputFilename(C.getArgs(), Val, BaseName, types::TY_Image);
Hans Wennborgf1a74252013-09-10 20:18:04 +00004061 } else if (JA.getType() == types::TY_Image) {
Hans Wennborg207fcf02013-08-12 21:56:42 +00004062 if (IsCLMode()) {
4063 // clang-cl uses BaseName for the executable name.
Douglas Katzmana67e50c2015-06-26 15:47:46 +00004064 NamedOutput =
4065 MakeCLOutputFilename(C.getArgs(), "", BaseName, types::TY_Image);
Samuel Antao59efaed2016-10-27 17:31:22 +00004066 } else {
Hans Wennborga7707222015-01-09 17:38:53 +00004067 SmallString<128> Output(getDefaultImageName());
Samuel Antao3b7e38b2016-10-27 18:14:55 +00004068 Output += OffloadingPrefix;
Samuel Antao59efaed2016-10-27 17:31:22 +00004069 if (MultipleArchs && !BoundArch.empty()) {
4070 Output += "-";
4071 Output.append(BoundArch);
4072 }
Chad Rosier35767232013-04-30 22:01:21 +00004073 NamedOutput = C.getArgs().MakeArgString(Output.c_str());
Nico Weber2ca4be92016-03-01 23:16:44 +00004074 }
4075 } else if (JA.getType() == types::TY_PCH && IsCLMode()) {
Malcolm Parsonsf76f6502016-11-02 10:39:27 +00004076 NamedOutput = C.getArgs().MakeArgString(GetClPchPath(C, BaseName));
Daniel Dunbar7a178a42009-03-17 17:53:55 +00004077 } else {
Hans Wennborg0a096a02013-09-05 17:05:56 +00004078 const char *Suffix = types::getTypeTempSuffix(JA.getType(), IsCLMode());
Daniel Dunbar7a178a42009-03-17 17:53:55 +00004079 assert(Suffix && "All types used for output should have a suffix.");
4080
4081 std::string::size_type End = std::string::npos;
4082 if (!types::appendSuffixForType(JA.getType()))
4083 End = BaseName.rfind('.');
Chad Rosier35767232013-04-30 22:01:21 +00004084 SmallString<128> Suffixed(BaseName.substr(0, End));
Samuel Antao3b7e38b2016-10-27 18:14:55 +00004085 Suffixed += OffloadingPrefix;
Mehdi Aminic50b1a22016-10-07 21:27:26 +00004086 if (MultipleArchs && !BoundArch.empty()) {
Chad Rosier35767232013-04-30 22:01:21 +00004087 Suffixed += "-";
4088 Suffixed.append(BoundArch);
4089 }
Bob Wilson23a55f12014-12-21 07:00:00 +00004090 // When using both -save-temps and -emit-llvm, use a ".tmp.bc" suffix for
4091 // the unoptimized bitcode so that it does not get overwritten by the ".bc"
4092 // optimized bitcode output.
4093 if (!AtTopLevel && C.getArgs().hasArg(options::OPT_emit_llvm) &&
4094 JA.getType() == types::TY_LLVM_BC)
4095 Suffixed += ".tmp";
Daniel Dunbar7a178a42009-03-17 17:53:55 +00004096 Suffixed += '.';
4097 Suffixed += Suffix;
4098 NamedOutput = C.getArgs().MakeArgString(Suffixed.c_str());
4099 }
4100
Reid Kleckner68eb60b2015-02-02 22:41:48 +00004101 // Prepend object file path if -save-temps=obj
4102 if (!AtTopLevel && isSaveTempsObj() && C.getArgs().hasArg(options::OPT_o) &&
4103 JA.getType() != types::TY_PCH) {
4104 Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o);
4105 SmallString<128> TempPath(FinalOutput->getValue());
4106 llvm::sys::path::remove_filename(TempPath);
4107 StringRef OutputFileName = llvm::sys::path::filename(NamedOutput);
4108 llvm::sys::path::append(TempPath, OutputFileName);
4109 NamedOutput = C.getArgs().MakeArgString(TempPath.c_str());
4110 }
4111
Chad Rosier62135492012-07-09 17:31:28 +00004112 // If we're saving temps and the temp file conflicts with the input file,
Chad Rosier5b58af02012-04-20 20:05:08 +00004113 // then avoid overwriting input file.
Reid Kleckner68eb60b2015-02-02 22:41:48 +00004114 if (!AtTopLevel && isSaveTempsEnabled() && NamedOutput == BaseName) {
Chad Rosier5b58af02012-04-20 20:05:08 +00004115 bool SameFile = false;
4116 SmallString<256> Result;
4117 llvm::sys::fs::current_path(Result);
4118 llvm::sys::path::append(Result, BaseName);
4119 llvm::sys::fs::equivalent(BaseInput, Result.c_str(), SameFile);
4120 // Must share the same path to conflict.
4121 if (SameFile) {
4122 StringRef Name = llvm::sys::path::filename(BaseInput);
4123 std::pair<StringRef, StringRef> Split = Name.split('.');
Douglas Katzmana67e50c2015-06-26 15:47:46 +00004124 std::string TmpName = GetTemporaryPath(
4125 Split.first, types::getTypeTempSuffix(JA.getType(), IsCLMode()));
Malcolm Parsonsf76f6502016-11-02 10:39:27 +00004126 return C.addTempFile(C.getArgs().MakeArgString(TmpName));
Chad Rosier5b58af02012-04-20 20:05:08 +00004127 }
Chad Rosierf8412cd2011-07-15 21:54:29 +00004128 }
4129
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00004130 // As an annoying special case, PCH generation doesn't strip the pathname.
Nico Weber8ab92192016-03-02 23:29:29 +00004131 if (JA.getType() == types::TY_PCH && !IsCLMode()) {
Michael J. Spencere1696752010-12-18 00:19:12 +00004132 llvm::sys::path::remove_filename(BasePath);
4133 if (BasePath.empty())
Daniel Dunbare6c83192009-03-18 09:58:30 +00004134 BasePath = NamedOutput;
4135 else
Michael J. Spencere1696752010-12-18 00:19:12 +00004136 llvm::sys::path::append(BasePath, NamedOutput);
Chad Rosier633dcdc2013-01-24 19:14:47 +00004137 return C.addResultFile(C.getArgs().MakeArgString(BasePath.c_str()), &JA);
Daniel Dunbar7a178a42009-03-17 17:53:55 +00004138 } else {
Chad Rosier633dcdc2013-01-24 19:14:47 +00004139 return C.addResultFile(NamedOutput, &JA);
Daniel Dunbar7a178a42009-03-17 17:53:55 +00004140 }
4141}
4142
Mehdi Amini12011172016-10-06 05:11:48 +00004143std::string Driver::GetFilePath(StringRef Name, const ToolChain &TC) const {
Chandler Carruth84559242010-03-22 01:52:07 +00004144 // Respect a limited subset of the '-Bprefix' functionality in GCC by
Logan Chiencd679fd2012-10-04 08:08:56 +00004145 // attempting to use this prefix when looking for file paths.
Douglas Katzman26eabf62015-06-24 15:10:30 +00004146 for (const std::string &Dir : PrefixDirs) {
Joerg Sonnenberger6165ab12011-03-21 13:51:29 +00004147 if (Dir.empty())
4148 continue;
Douglas Katzman26eabf62015-06-24 15:10:30 +00004149 SmallString<128> P(Dir[0] == '=' ? SysRoot + Dir.substr(1) : Dir);
Rafael Espindola609a6642013-06-24 18:33:43 +00004150 llvm::sys::path::append(P, Name);
4151 if (llvm::sys::fs::exists(Twine(P)))
Chandler Carruth84559242010-03-22 01:52:07 +00004152 return P.str();
4153 }
4154
Petr Hosek916a4672017-08-10 04:16:38 +00004155 SmallString<128> R(ResourceDir);
4156 llvm::sys::path::append(R, Name);
4157 if (llvm::sys::fs::exists(Twine(R)))
4158 return R.str();
4159
4160 SmallString<128> P(TC.getCompilerRTPath());
Rafael Espindola609a6642013-06-24 18:33:43 +00004161 llvm::sys::path::append(P, Name);
4162 if (llvm::sys::fs::exists(Twine(P)))
Peter Collingbournefa9771f2011-09-06 02:08:31 +00004163 return P.str();
4164
Douglas Katzman26eabf62015-06-24 15:10:30 +00004165 for (const std::string &Dir : TC.getFilePaths()) {
Joerg Sonnenberger6165ab12011-03-21 13:51:29 +00004166 if (Dir.empty())
4167 continue;
Douglas Katzman26eabf62015-06-24 15:10:30 +00004168 SmallString<128> P(Dir[0] == '=' ? SysRoot + Dir.substr(1) : Dir);
Rafael Espindola609a6642013-06-24 18:33:43 +00004169 llvm::sys::path::append(P, Name);
4170 if (llvm::sys::fs::exists(Twine(P)))
Daniel Dunbar1ce81532009-09-09 22:33:00 +00004171 return P.str();
Daniel Dunbar68b01a02009-03-18 20:26:19 +00004172 }
4173
Daniel Dunbar1ce81532009-09-09 22:33:00 +00004174 return Name;
Daniel Dunbar5e0f6af2009-03-13 00:51:18 +00004175}
4176
Douglas Katzmana67e50c2015-06-26 15:47:46 +00004177void Driver::generatePrefixedToolNames(
Mehdi Amini12011172016-10-06 05:11:48 +00004178 StringRef Tool, const ToolChain &TC,
Douglas Katzmana67e50c2015-06-26 15:47:46 +00004179 SmallVectorImpl<std::string> &Names) const {
Petr Hosekdd38d932018-05-29 22:35:39 +00004180 // FIXME: Needs a better variable than TargetTriple
4181 Names.emplace_back((TargetTriple + "-" + Tool).str());
Benjamin Kramer3204b152015-05-29 19:42:19 +00004182 Names.emplace_back(Tool);
Vasileios Kalintirisc744e122015-11-12 15:26:54 +00004183
4184 // Allow the discovery of tools prefixed with LLVM's default target triple.
Petr Hosekdd38d932018-05-29 22:35:39 +00004185 std::string DefaultTargetTriple = llvm::sys::getDefaultTargetTriple();
4186 if (DefaultTargetTriple != TargetTriple)
4187 Names.emplace_back((DefaultTargetTriple + "-" + Tool).str());
Saleem Abdulrasoolf0ba6ce2014-10-25 23:33:21 +00004188}
4189
Benjamin Kramer7111b912014-11-04 20:26:01 +00004190static bool ScanDirForExecutable(SmallString<128> &Dir,
4191 ArrayRef<std::string> Names) {
Saleem Abdulrasoolf0ba6ce2014-10-25 23:33:21 +00004192 for (const auto &Name : Names) {
4193 llvm::sys::path::append(Dir, Name);
4194 if (llvm::sys::fs::can_execute(Twine(Dir)))
4195 return true;
4196 llvm::sys::path::remove_filename(Dir);
4197 }
4198 return false;
4199}
4200
Mehdi Amini12011172016-10-06 05:11:48 +00004201std::string Driver::GetProgramPath(StringRef Name, const ToolChain &TC) const {
Saleem Abdulrasoolf0ba6ce2014-10-25 23:33:21 +00004202 SmallVector<std::string, 2> TargetSpecificExecutables;
4203 generatePrefixedToolNames(Name, TC, TargetSpecificExecutables);
4204
Chandler Carruth84559242010-03-22 01:52:07 +00004205 // Respect a limited subset of the '-Bprefix' functionality in GCC by
Logan Chiencd679fd2012-10-04 08:08:56 +00004206 // attempting to use this prefix when looking for program paths.
Saleem Abdulrasool23d99b12014-09-16 03:48:32 +00004207 for (const auto &PrefixDir : PrefixDirs) {
4208 if (llvm::sys::fs::is_directory(PrefixDir)) {
4209 SmallString<128> P(PrefixDir);
Saleem Abdulrasoolf0ba6ce2014-10-25 23:33:21 +00004210 if (ScanDirForExecutable(P, TargetSpecificExecutables))
Rafael Espindola8be5c052013-06-19 13:24:29 +00004211 return P.str();
Simon Atanasyana47ba292012-10-31 14:39:28 +00004212 } else {
Mehdi Amini12011172016-10-06 05:11:48 +00004213 SmallString<128> P((PrefixDir + Name).str());
Rafael Espindola609a6642013-06-24 18:33:43 +00004214 if (llvm::sys::fs::can_execute(Twine(P)))
Rafael Espindola8be5c052013-06-19 13:24:29 +00004215 return P.str();
Simon Atanasyan86bdab72012-10-31 12:01:53 +00004216 }
Chandler Carruth84559242010-03-22 01:52:07 +00004217 }
4218
Daniel Dunbar68b01a02009-03-18 20:26:19 +00004219 const ToolChain::path_list &List = TC.getProgramPaths();
Saleem Abdulrasool23d99b12014-09-16 03:48:32 +00004220 for (const auto &Path : List) {
4221 SmallString<128> P(Path);
Saleem Abdulrasoolf0ba6ce2014-10-25 23:33:21 +00004222 if (ScanDirForExecutable(P, TargetSpecificExecutables))
Rafael Espindola8be5c052013-06-19 13:24:29 +00004223 return P.str();
Daniel Dunbar68b01a02009-03-18 20:26:19 +00004224 }
4225
Daniel Dunbar76ce7412009-03-23 16:15:50 +00004226 // If all else failed, search the path.
Michael J. Spencerb011d482014-11-07 21:30:32 +00004227 for (const auto &TargetSpecificExecutable : TargetSpecificExecutables)
4228 if (llvm::ErrorOr<std::string> P =
4229 llvm::sys::findProgramByName(TargetSpecificExecutable))
Michael J. Spencer04162ea2014-11-04 01:30:55 +00004230 return *P;
Daniel Dunbar6f668772009-03-18 21:34:08 +00004231
Daniel Dunbar1ce81532009-09-09 22:33:00 +00004232 return Name;
Daniel Dunbar5e0f6af2009-03-13 00:51:18 +00004233}
4234
Mehdi Amini12011172016-10-06 05:11:48 +00004235std::string Driver::GetTemporaryPath(StringRef Prefix, StringRef Suffix) const {
Rafael Espindola37d229d2013-06-25 04:26:55 +00004236 SmallString<128> Path;
Rafael Espindolac0809172014-06-12 14:02:15 +00004237 std::error_code EC = llvm::sys::fs::createTemporaryFile(Prefix, Suffix, Path);
Rafael Espindola37d229d2013-06-25 04:26:55 +00004238 if (EC) {
4239 Diag(clang::diag::err_unable_to_make_temp) << EC.message();
Daniel Dunbare627c1c2009-03-18 19:34:39 +00004240 return "";
4241 }
4242
Rafael Espindola37d229d2013-06-25 04:26:55 +00004243 return Path.str();
Daniel Dunbare627c1c2009-03-18 19:34:39 +00004244}
4245
Nico Weber2ca4be92016-03-01 23:16:44 +00004246std::string Driver::GetClPchPath(Compilation &C, StringRef BaseName) const {
4247 SmallString<128> Output;
4248 if (Arg *FpArg = C.getArgs().getLastArg(options::OPT__SLASH_Fp)) {
4249 // FIXME: If anybody needs it, implement this obscure rule:
4250 // "If you specify a directory without a file name, the default file name
4251 // is VCx0.pch., where x is the major version of Visual C++ in use."
4252 Output = FpArg->getValue();
4253
4254 // "If you do not specify an extension as part of the path name, an
4255 // extension of .pch is assumed. "
4256 if (!llvm::sys::path::has_extension(Output))
4257 Output += ".pch";
4258 } else {
4259 Output = BaseName;
4260 llvm::sys::path::replace_extension(Output, ".pch");
4261 }
4262 return Output.str();
4263}
4264
Chandler Carruth2ad5de12012-01-25 11:01:57 +00004265const ToolChain &Driver::getToolChain(const ArgList &Args,
Artem Belevich959e0542015-07-10 19:47:55 +00004266 const llvm::Triple &Target) const {
Chandler Carruth2ad5de12012-01-25 11:01:57 +00004267
David Blaikie6ad71012017-01-13 18:53:43 +00004268 auto &TC = ToolChains[Target.str()];
Chandler Carruth2ad5de12012-01-25 11:01:57 +00004269 if (!TC) {
4270 switch (Target.getOS()) {
Reid Kleckner330fb172016-05-11 16:19:05 +00004271 case llvm::Triple::Haiku:
David Blaikie6ad71012017-01-13 18:53:43 +00004272 TC = llvm::make_unique<toolchains::Haiku>(*this, Target, Args);
Reid Kleckner330fb172016-05-11 16:19:05 +00004273 break;
Ed Schouten4dabea22017-06-25 08:29:09 +00004274 case llvm::Triple::Ananas:
4275 TC = llvm::make_unique<toolchains::Ananas>(*this, Target, Args);
4276 break;
Ed Schouten3c3e58c2015-03-26 11:13:44 +00004277 case llvm::Triple::CloudABI:
David Blaikie6ad71012017-01-13 18:53:43 +00004278 TC = llvm::make_unique<toolchains::CloudABI>(*this, Target, Args);
Ed Schouten3c3e58c2015-03-26 11:13:44 +00004279 break;
Chandler Carruth2ad5de12012-01-25 11:01:57 +00004280 case llvm::Triple::Darwin:
4281 case llvm::Triple::MacOSX:
4282 case llvm::Triple::IOS:
Tim Northover6f3ff222015-10-30 16:30:27 +00004283 case llvm::Triple::TvOS:
4284 case llvm::Triple::WatchOS:
David Blaikie6ad71012017-01-13 18:53:43 +00004285 TC = llvm::make_unique<toolchains::DarwinClang>(*this, Target, Args);
Chandler Carruth2ad5de12012-01-25 11:01:57 +00004286 break;
4287 case llvm::Triple::DragonFly:
David Blaikie6ad71012017-01-13 18:53:43 +00004288 TC = llvm::make_unique<toolchains::DragonFly>(*this, Target, Args);
Chandler Carruth2ad5de12012-01-25 11:01:57 +00004289 break;
4290 case llvm::Triple::OpenBSD:
David Blaikie6ad71012017-01-13 18:53:43 +00004291 TC = llvm::make_unique<toolchains::OpenBSD>(*this, Target, Args);
Chandler Carruth2ad5de12012-01-25 11:01:57 +00004292 break;
4293 case llvm::Triple::NetBSD:
David Blaikie6ad71012017-01-13 18:53:43 +00004294 TC = llvm::make_unique<toolchains::NetBSD>(*this, Target, Args);
Chandler Carruth2ad5de12012-01-25 11:01:57 +00004295 break;
4296 case llvm::Triple::FreeBSD:
David Blaikie6ad71012017-01-13 18:53:43 +00004297 TC = llvm::make_unique<toolchains::FreeBSD>(*this, Target, Args);
Chandler Carruth2ad5de12012-01-25 11:01:57 +00004298 break;
4299 case llvm::Triple::Minix:
David Blaikie6ad71012017-01-13 18:53:43 +00004300 TC = llvm::make_unique<toolchains::Minix>(*this, Target, Args);
Chandler Carruth2ad5de12012-01-25 11:01:57 +00004301 break;
4302 case llvm::Triple::Linux:
Andrey Turetskiy4798eb62016-06-16 10:36:09 +00004303 case llvm::Triple::ELFIAMCU:
Chandler Carruthcf705b22012-01-25 21:03:58 +00004304 if (Target.getArch() == llvm::Triple::hexagon)
David Blaikie6ad71012017-01-13 18:53:43 +00004305 TC = llvm::make_unique<toolchains::HexagonToolChain>(*this, Target,
4306 Args);
Vasileios Kalintirisc744e122015-11-12 15:26:54 +00004307 else if ((Target.getVendor() == llvm::Triple::MipsTechnologies) &&
4308 !Target.hasEnvironment())
David Blaikie6ad71012017-01-13 18:53:43 +00004309 TC = llvm::make_unique<toolchains::MipsLLVMToolChain>(*this, Target,
4310 Args);
Chandler Carruthcf705b22012-01-25 21:03:58 +00004311 else
David Blaikie6ad71012017-01-13 18:53:43 +00004312 TC = llvm::make_unique<toolchains::Linux>(*this, Target, Args);
Chandler Carruth2ad5de12012-01-25 11:01:57 +00004313 break;
Derek Schuff6ab52fa2015-03-30 20:31:33 +00004314 case llvm::Triple::NaCl:
David Blaikie6ad71012017-01-13 18:53:43 +00004315 TC = llvm::make_unique<toolchains::NaClToolChain>(*this, Target, Args);
Derek Schuff6ab52fa2015-03-30 20:31:33 +00004316 break;
Petr Hosek62e1d232016-10-06 06:08:09 +00004317 case llvm::Triple::Fuchsia:
David Blaikie6ad71012017-01-13 18:53:43 +00004318 TC = llvm::make_unique<toolchains::Fuchsia>(*this, Target, Args);
Petr Hosek62e1d232016-10-06 06:08:09 +00004319 break;
David Chisnallf571cde2012-02-15 13:39:01 +00004320 case llvm::Triple::Solaris:
David Blaikie6ad71012017-01-13 18:53:43 +00004321 TC = llvm::make_unique<toolchains::Solaris>(*this, Target, Args);
David Chisnallf571cde2012-02-15 13:39:01 +00004322 break;
Tom Stellard8fa33092015-07-18 01:49:05 +00004323 case llvm::Triple::AMDHSA:
David Blaikie6ad71012017-01-13 18:53:43 +00004324 TC = llvm::make_unique<toolchains::AMDGPUToolChain>(*this, Target, Args);
Tom Stellard8fa33092015-07-18 01:49:05 +00004325 break;
Chandler Carruth2ad5de12012-01-25 11:01:57 +00004326 case llvm::Triple::Win32:
Saleem Abdulrasool377066a2014-03-27 22:50:18 +00004327 switch (Target.getEnvironment()) {
4328 default:
4329 if (Target.isOSBinFormatELF())
David Blaikie6ad71012017-01-13 18:53:43 +00004330 TC = llvm::make_unique<toolchains::Generic_ELF>(*this, Target, Args);
Saleem Abdulrasool377066a2014-03-27 22:50:18 +00004331 else if (Target.isOSBinFormatMachO())
David Blaikie6ad71012017-01-13 18:53:43 +00004332 TC = llvm::make_unique<toolchains::MachO>(*this, Target, Args);
Saleem Abdulrasool377066a2014-03-27 22:50:18 +00004333 else
David Blaikie6ad71012017-01-13 18:53:43 +00004334 TC = llvm::make_unique<toolchains::Generic_GCC>(*this, Target, Args);
Saleem Abdulrasool377066a2014-03-27 22:50:18 +00004335 break;
4336 case llvm::Triple::GNU:
David Blaikie6ad71012017-01-13 18:53:43 +00004337 TC = llvm::make_unique<toolchains::MinGW>(*this, Target, Args);
Saleem Abdulrasool377066a2014-03-27 22:50:18 +00004338 break;
Saleem Abdulrasool543a78b2014-10-24 03:13:37 +00004339 case llvm::Triple::Itanium:
David Blaikie6ad71012017-01-13 18:53:43 +00004340 TC = llvm::make_unique<toolchains::CrossWindowsToolChain>(*this, Target,
4341 Args);
Saleem Abdulrasool543a78b2014-10-24 03:13:37 +00004342 break;
Saleem Abdulrasool377066a2014-03-27 22:50:18 +00004343 case llvm::Triple::MSVC:
4344 case llvm::Triple::UnknownEnvironment:
Dave Leef96bedf2017-11-06 21:18:05 +00004345 if (Args.getLastArgValue(options::OPT_fuse_ld_EQ)
4346 .startswith_lower("bfd"))
4347 TC = llvm::make_unique<toolchains::CrossWindowsToolChain>(
4348 *this, Target, Args);
4349 else
4350 TC =
4351 llvm::make_unique<toolchains::MSVCToolChain>(*this, Target, Args);
Saleem Abdulrasool377066a2014-03-27 22:50:18 +00004352 break;
4353 }
Chandler Carruth2ad5de12012-01-25 11:01:57 +00004354 break;
Filipe Cabecinhasc888e192015-10-14 12:25:43 +00004355 case llvm::Triple::PS4:
David Blaikie6ad71012017-01-13 18:53:43 +00004356 TC = llvm::make_unique<toolchains::PS4CPU>(*this, Target, Args);
Filipe Cabecinhasc888e192015-10-14 12:25:43 +00004357 break;
David L Kreitzerd397ea42016-10-14 20:44:33 +00004358 case llvm::Triple::Contiki:
David Blaikie6ad71012017-01-13 18:53:43 +00004359 TC = llvm::make_unique<toolchains::Contiki>(*this, Target, Args);
David L Kreitzerd397ea42016-10-14 20:44:33 +00004360 break;
Chandler Carruth2ad5de12012-01-25 11:01:57 +00004361 default:
Douglas Katzman9f5e70e2015-05-26 18:01:33 +00004362 // Of these targets, Hexagon is the only one that might have
4363 // an OS of Linux, in which case it got handled above already.
Douglas Katzman15a63ed2015-08-12 18:36:12 +00004364 switch (Target.getArch()) {
4365 case llvm::Triple::tce:
David Blaikie6ad71012017-01-13 18:53:43 +00004366 TC = llvm::make_unique<toolchains::TCEToolChain>(*this, Target, Args);
Douglas Katzman15a63ed2015-08-12 18:36:12 +00004367 break;
Pekka Jaaskelainen67354482016-11-16 15:22:31 +00004368 case llvm::Triple::tcele:
David Blaikie6ad71012017-01-13 18:53:43 +00004369 TC = llvm::make_unique<toolchains::TCELEToolChain>(*this, Target, Args);
Pekka Jaaskelainen67354482016-11-16 15:22:31 +00004370 break;
Douglas Katzman15a63ed2015-08-12 18:36:12 +00004371 case llvm::Triple::hexagon:
David Blaikie6ad71012017-01-13 18:53:43 +00004372 TC = llvm::make_unique<toolchains::HexagonToolChain>(*this, Target,
4373 Args);
Douglas Katzman15a63ed2015-08-12 18:36:12 +00004374 break;
Jacques Pienaard964cc22016-03-28 21:02:54 +00004375 case llvm::Triple::lanai:
David Blaikie6ad71012017-01-13 18:53:43 +00004376 TC = llvm::make_unique<toolchains::LanaiToolChain>(*this, Target, Args);
Jacques Pienaard964cc22016-03-28 21:02:54 +00004377 break;
Douglas Katzman15a63ed2015-08-12 18:36:12 +00004378 case llvm::Triple::xcore:
David Blaikie6ad71012017-01-13 18:53:43 +00004379 TC = llvm::make_unique<toolchains::XCoreToolChain>(*this, Target, Args);
Douglas Katzman15a63ed2015-08-12 18:36:12 +00004380 break;
Dan Gohmanc2853072015-09-03 22:51:53 +00004381 case llvm::Triple::wasm32:
4382 case llvm::Triple::wasm64:
David Blaikie6ad71012017-01-13 18:53:43 +00004383 TC = llvm::make_unique<toolchains::WebAssembly>(*this, Target, Args);
Dan Gohmanc2853072015-09-03 22:51:53 +00004384 break;
Dylan McKay924fa3a2017-01-05 05:20:27 +00004385 case llvm::Triple::avr:
David Blaikie6ad71012017-01-13 18:53:43 +00004386 TC = llvm::make_unique<toolchains::AVRToolChain>(*this, Target, Args);
Dylan McKay924fa3a2017-01-05 05:20:27 +00004387 break;
Douglas Katzman15a63ed2015-08-12 18:36:12 +00004388 default:
Douglas Katzmand6e597c2015-09-17 19:56:40 +00004389 if (Target.getVendor() == llvm::Triple::Myriad)
David Blaikie6ad71012017-01-13 18:53:43 +00004390 TC = llvm::make_unique<toolchains::MyriadToolChain>(*this, Target,
4391 Args);
Jonathan Roelofs901c7762017-05-25 15:42:13 +00004392 else if (toolchains::BareMetal::handlesTarget(Target))
4393 TC = llvm::make_unique<toolchains::BareMetal>(*this, Target, Args);
Douglas Katzmand6e597c2015-09-17 19:56:40 +00004394 else if (Target.isOSBinFormatELF())
David Blaikie6ad71012017-01-13 18:53:43 +00004395 TC = llvm::make_unique<toolchains::Generic_ELF>(*this, Target, Args);
Douglas Katzman15a63ed2015-08-12 18:36:12 +00004396 else if (Target.isOSBinFormatMachO())
David Blaikie6ad71012017-01-13 18:53:43 +00004397 TC = llvm::make_unique<toolchains::MachO>(*this, Target, Args);
Douglas Katzman15a63ed2015-08-12 18:36:12 +00004398 else
David Blaikie6ad71012017-01-13 18:53:43 +00004399 TC = llvm::make_unique<toolchains::Generic_GCC>(*this, Target, Args);
Douglas Katzman15a63ed2015-08-12 18:36:12 +00004400 }
Chandler Carruth2ad5de12012-01-25 11:01:57 +00004401 }
4402 }
Justin Lebar66c4fd72016-11-18 00:41:22 +00004403
4404 // Intentionally omitted from the switch above: llvm::Triple::CUDA. CUDA
4405 // compiles always need two toolchains, the CUDA toolchain and the host
4406 // toolchain. So the only valid way to create a CUDA toolchain is via
4407 // CreateOffloadingDeviceToolChains.
4408
Chandler Carruth2ad5de12012-01-25 11:01:57 +00004409 return *TC;
Daniel Dunbar4dff6a42009-03-10 23:41:59 +00004410}
Daniel Dunbar8fa879d2009-03-24 18:57:02 +00004411
Rafael Espindola2f69d402013-03-18 15:33:26 +00004412bool Driver::ShouldUseClangCompiler(const JobAction &JA) const {
Douglas Katzman00249092015-06-12 15:45:21 +00004413 // Say "no" if there is not exactly one input of a type clang understands.
Nico Weber5a459f82016-02-23 19:30:43 +00004414 if (JA.size() != 1 ||
4415 !types::isAcceptedByClang((*JA.input_begin())->getType()))
Nick Lewycky5cc9ebb2012-11-15 05:36:36 +00004416 return false;
4417
Douglas Katzman00249092015-06-12 15:45:21 +00004418 // And say "no" if this is not a kind of action clang understands.
Nick Lewycky5cc9ebb2012-11-15 05:36:36 +00004419 if (!isa<PreprocessJobAction>(JA) && !isa<PrecompileJobAction>(JA) &&
Bob Wilson23a55f12014-12-21 07:00:00 +00004420 !isa<CompileJobAction>(JA) && !isa<BackendJobAction>(JA))
Nick Lewycky5cc9ebb2012-11-15 05:36:36 +00004421 return false;
4422
4423 return true;
4424}
4425
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00004426/// GetReleaseVersion - Parse (([0-9]+)(.([0-9]+)(.([0-9]+)?))?)? and return the
4427/// grouped values as integers. Numbers which are not provided are set to 0.
Daniel Dunbarc7fd57a2009-03-26 15:58:36 +00004428///
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00004429/// \return True if the entire string was parsed (9.2), or all groups were
4430/// parsed (10.3.5extrastuff).
Mehdi Amini12011172016-10-06 05:11:48 +00004431bool Driver::GetReleaseVersion(StringRef Str, unsigned &Major, unsigned &Minor,
4432 unsigned &Micro, bool &HadExtra) {
Daniel Dunbarc7fd57a2009-03-26 15:58:36 +00004433 HadExtra = false;
4434
4435 Major = Minor = Micro = 0;
Mehdi Amini12011172016-10-06 05:11:48 +00004436 if (Str.empty())
Bob Wilson433cb312015-04-07 01:03:35 +00004437 return false;
Daniel Dunbarc7fd57a2009-03-26 15:58:36 +00004438
Mehdi Amini12011172016-10-06 05:11:48 +00004439 if (Str.consumeInteger(10, Major))
4440 return false;
4441 if (Str.empty())
Daniel Dunbarc7fd57a2009-03-26 15:58:36 +00004442 return true;
Mehdi Amini12011172016-10-06 05:11:48 +00004443 if (Str[0] != '.')
Daniel Dunbarc7fd57a2009-03-26 15:58:36 +00004444 return false;
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00004445
Mehdi Amini12011172016-10-06 05:11:48 +00004446 Str = Str.drop_front(1);
Daniel Dunbarc7fd57a2009-03-26 15:58:36 +00004447
Mehdi Amini12011172016-10-06 05:11:48 +00004448 if (Str.consumeInteger(10, Minor))
Daniel Dunbarc7fd57a2009-03-26 15:58:36 +00004449 return false;
Mehdi Amini12011172016-10-06 05:11:48 +00004450 if (Str.empty())
4451 return true;
4452 if (Str[0] != '.')
4453 return false;
4454 Str = Str.drop_front(1);
4455
4456 if (Str.consumeInteger(10, Micro))
4457 return false;
4458 if (!Str.empty())
4459 HadExtra = true;
Daniel Dunbarc7fd57a2009-03-26 15:58:36 +00004460 return true;
4461}
Hans Wennborg6ddc6902013-07-27 00:23:45 +00004462
Bruno Cardoso Lopes8ed5cac2016-03-31 02:45:46 +00004463/// Parse digits from a string \p Str and fulfill \p Digits with
4464/// the parsed numbers. This method assumes that the max number of
4465/// digits to look for is equal to Digits.size().
4466///
4467/// \return True if the entire string was parsed and there are
4468/// no extra characters remaining at the end.
Mehdi Amini12011172016-10-06 05:11:48 +00004469bool Driver::GetReleaseVersion(StringRef Str,
Bruno Cardoso Lopes8ed5cac2016-03-31 02:45:46 +00004470 MutableArrayRef<unsigned> Digits) {
Mehdi Amini12011172016-10-06 05:11:48 +00004471 if (Str.empty())
Bruno Cardoso Lopes8ed5cac2016-03-31 02:45:46 +00004472 return false;
4473
Bruno Cardoso Lopes8ed5cac2016-03-31 02:45:46 +00004474 unsigned CurDigit = 0;
4475 while (CurDigit < Digits.size()) {
Mehdi Amini12011172016-10-06 05:11:48 +00004476 unsigned Digit;
4477 if (Str.consumeInteger(10, Digit))
Bruno Cardoso Lopes8ed5cac2016-03-31 02:45:46 +00004478 return false;
Mehdi Amini12011172016-10-06 05:11:48 +00004479 Digits[CurDigit] = Digit;
4480 if (Str.empty())
4481 return true;
4482 if (Str[0] != '.')
4483 return false;
4484 Str = Str.drop_front(1);
Bruno Cardoso Lopes8ed5cac2016-03-31 02:45:46 +00004485 CurDigit++;
4486 }
4487
4488 // More digits than requested, bail out...
4489 return false;
4490}
4491
Hans Wennborg6ddc6902013-07-27 00:23:45 +00004492std::pair<unsigned, unsigned> Driver::getIncludeExcludeOptionFlagMasks() const {
4493 unsigned IncludedFlagsBitmask = 0;
Rafael Espindolacc707bc2013-09-25 15:54:41 +00004494 unsigned ExcludedFlagsBitmask = options::NoDriverOption;
Hans Wennborg6ddc6902013-07-27 00:23:45 +00004495
4496 if (Mode == CLMode) {
Hans Wennborg19076102013-07-31 20:51:53 +00004497 // Include CL and Core options.
4498 IncludedFlagsBitmask |= options::CLOption;
4499 IncludedFlagsBitmask |= options::CoreOption;
Hans Wennborg6ddc6902013-07-27 00:23:45 +00004500 } else {
4501 ExcludedFlagsBitmask |= options::CLOption;
4502 }
4503
4504 return std::make_pair(IncludedFlagsBitmask, ExcludedFlagsBitmask);
4505}
Benjamin Kramerab88f622014-03-25 18:02:07 +00004506
Douglas Katzmanf08fadf2015-06-04 14:40:44 +00004507bool clang::driver::isOptimizationLevelFast(const ArgList &Args) {
Benjamin Kramerab88f622014-03-25 18:02:07 +00004508 return Args.hasFlag(options::OPT_Ofast, options::OPT_O_Group, false);
4509}