blob: 932a54fad428f4fd589d6eb827a76590e3251f10 [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"
Reid Kleckner898229a2013-06-14 17:17:23 +000060#include "llvm/Option/Arg.h"
61#include "llvm/Option/ArgList.h"
Chandler Carruth5553d0d2014-01-07 11:51:46 +000062#include "llvm/Option/OptSpecifier.h"
Reid Kleckner898229a2013-06-14 17:17:23 +000063#include "llvm/Option/OptTable.h"
64#include "llvm/Option/Option.h"
Serge Pavlov208ac652018-01-01 13:27:01 +000065#include "llvm/Support/CommandLine.h"
David Blaikie79000202011-09-23 05:57:42 +000066#include "llvm/Support/ErrorHandling.h"
Michael J. Spencerf28df4c2010-12-17 21:22:22 +000067#include "llvm/Support/FileSystem.h"
Michael J. Spencer8aaf4992010-11-29 18:12:39 +000068#include "llvm/Support/Path.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000069#include "llvm/Support/PrettyStackTrace.h"
Hans Wennborg23d26a32014-06-18 17:21:50 +000070#include "llvm/Support/Process.h"
Michael J. Spencer8aaf4992010-11-29 18:12:39 +000071#include "llvm/Support/Program.h"
Dimitry Andric81c40422017-06-06 21:54:21 +000072#include "llvm/Support/TargetRegistry.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000073#include "llvm/Support/raw_ostream.h"
Serge Pavlov208ac652018-01-01 13:27:01 +000074#include "llvm/Support/StringSaver.h"
Dylan Noblesmith4f4e7452012-02-02 00:40:14 +000075#include <map>
Ahmed Charlesdfca6f92014-03-09 11:36:40 +000076#include <memory>
Benjamin Kramercfeacf52016-05-27 14:27:13 +000077#include <utility>
Bruno Cardoso Lopes02681c42016-11-17 21:41:22 +000078#if LLVM_ON_UNIX
79#include <unistd.h> // getpid
80#endif
Dylan Noblesmith86780e92012-02-01 14:25:28 +000081
Daniel Dunbarb2cd66b2009-03-04 20:49:20 +000082using namespace clang::driver;
Chris Lattnerada1c912009-03-26 05:56:24 +000083using namespace clang;
Reid Kleckner898229a2013-06-14 17:17:23 +000084using namespace llvm::opt;
Daniel Dunbarb2cd66b2009-03-04 20:49:20 +000085
Reid Kleckner68eb60b2015-02-02 22:41:48 +000086Driver::Driver(StringRef ClangExecutable, StringRef DefaultTargetTriple,
Benjamin Kramerd45b2052015-10-07 15:48:01 +000087 DiagnosticsEngine &Diags,
88 IntrusiveRefCntPtr<vfs::FileSystem> VFS)
Benjamin Kramercfeacf52016-05-27 14:27:13 +000089 : Opts(createDriverOptTable()), Diags(Diags), VFS(std::move(VFS)),
90 Mode(GCCMode), SaveTemps(SaveTempsNone), BitcodeEmbed(EmbedNone),
91 LTOMode(LTOK_None), ClangExecutable(ClangExecutable),
Alex Lorenz045c5142018-04-07 00:03:27 +000092 SysRoot(DEFAULT_SYSROOT), DriverTitle("clang LLVM compiler"),
93 CCPrintOptionsFilename(nullptr), CCPrintHeadersFilename(nullptr),
94 CCLogDiagnosticsFilename(nullptr), CCCPrintBindings(false),
95 CCPrintOptions(false), CCPrintHeaders(false), CCLogDiagnostics(false),
Vedant Kumarf2030b92016-07-18 19:56:33 +000096 CCGenDiagnostics(false), DefaultTargetTriple(DefaultTargetTriple),
Alex Lorenz045c5142018-04-07 00:03:27 +000097 CCCGenericGCCName(""), Saver(Alloc), CheckInputsExist(true),
98 CCCUsePCH(true), GenReproducer(false),
99 SuppressMissingInputWarning(false) {
Daniel Dunbar3f3e2cd2010-01-20 02:35:16 +0000100
Benjamin Kramerd45b2052015-10-07 15:48:01 +0000101 // Provide a sane fallback if no VFS is specified.
102 if (!this->VFS)
103 this->VFS = vfs::getRealFileSystem();
104
Sumanth Gundapaneni3a1592942015-03-03 20:43:12 +0000105 Name = llvm::sys::path::filename(ClangExecutable);
Douglas Katzmana67e50c2015-06-26 15:47:46 +0000106 Dir = llvm::sys::path::parent_path(ClangExecutable);
Benjamin Kramerf420dda2015-10-13 15:19:32 +0000107 InstalledDir = Dir; // Provide a sensible default installed dir.
Bob Wilsona20a1da2013-03-23 05:17:59 +0000108
Serge Pavlov208ac652018-01-01 13:27:01 +0000109#if defined(CLANG_CONFIG_FILE_SYSTEM_DIR)
110 SystemConfigDir = CLANG_CONFIG_FILE_SYSTEM_DIR;
111#endif
112#if defined(CLANG_CONFIG_FILE_USER_DIR)
113 UserConfigDir = CLANG_CONFIG_FILE_USER_DIR;
114#endif
115
Bob Wilsona20a1da2013-03-23 05:17:59 +0000116 // Compute the path to the resource directory.
117 StringRef ClangResourceDir(CLANG_RESOURCE_DIR);
118 SmallString<128> P(Dir);
Chandler Carruthfd3cc702014-12-29 12:09:08 +0000119 if (ClangResourceDir != "") {
Bob Wilsona20a1da2013-03-23 05:17:59 +0000120 llvm::sys::path::append(P, ClangResourceDir);
Chandler Carruthfd3cc702014-12-29 12:09:08 +0000121 } else {
122 StringRef ClangLibdirSuffix(CLANG_LIBDIR_SUFFIX);
Argyrios Kyrtzidisbcae0472017-02-25 18:14:35 +0000123 P = llvm::sys::path::parent_path(Dir);
124 llvm::sys::path::append(P, Twine("lib") + ClangLibdirSuffix, "clang",
Chandler Carruthfd3cc702014-12-29 12:09:08 +0000125 CLANG_VERSION_STRING);
126 }
Bob Wilsona20a1da2013-03-23 05:17:59 +0000127 ResourceDir = P.str();
Daniel Dunbar544ecd12009-03-02 19:59:07 +0000128}
129
Zachary Turneraff19c32016-08-12 17:47:52 +0000130void Driver::ParseDriverMode(StringRef ProgramName,
131 ArrayRef<const char *> Args) {
Martin Storsjo1fab23d2018-04-25 21:23:59 +0000132 if (ClangNameParts.isEmpty())
133 ClangNameParts = ToolChain::getTargetAndModeFromProgramName(ProgramName);
Serge Pavlov4e769842017-08-29 05:22:26 +0000134 setDriverModeFromOption(ClangNameParts.DriverMode);
Hans Wennborg70850d82013-07-18 20:29:38 +0000135
Douglas Katzman6bbffc42015-06-25 18:51:37 +0000136 for (const char *ArgPtr : Args) {
Erich Keane258f0592018-02-07 00:19:58 +0000137 // Ignore nullptrs, they are the response file's EOL markers.
Douglas Katzman6bbffc42015-06-25 18:51:37 +0000138 if (ArgPtr == nullptr)
Reid Kleckneraf5fd6a2014-08-22 19:29:30 +0000139 continue;
Douglas Katzman6bbffc42015-06-25 18:51:37 +0000140 const StringRef Arg = ArgPtr;
Zachary Turneraff19c32016-08-12 17:47:52 +0000141 setDriverModeFromOption(Arg);
Hans Wennborg70850d82013-07-18 20:29:38 +0000142 }
143}
144
Zachary Turneraff19c32016-08-12 17:47:52 +0000145void Driver::setDriverModeFromOption(StringRef Opt) {
146 const std::string OptName =
147 getOpts().getOption(options::OPT_driver_mode).getPrefixedName();
148 if (!Opt.startswith(OptName))
149 return;
150 StringRef Value = Opt.drop_front(OptName.size());
151
Erich Keane2908a042018-02-12 17:47:01 +0000152 if (auto M = llvm::StringSwitch<llvm::Optional<DriverMode>>(Value)
153 .Case("gcc", GCCMode)
154 .Case("g++", GXXMode)
155 .Case("cpp", CPPMode)
156 .Case("cl", CLMode)
157 .Default(None))
158 Mode = *M;
Zachary Turneraff19c32016-08-12 17:47:52 +0000159 else
160 Diag(diag::err_drv_unsupported_option_argument) << OptName << Value;
161}
162
Benjamin Kramer43c0f482017-06-30 13:21:27 +0000163InputArgList Driver::ParseArgStrings(ArrayRef<const char *> ArgStrings,
164 bool &ContainsError) {
Daniel Dunbar2608c542009-03-18 01:38:48 +0000165 llvm::PrettyStackTraceString CrashInfo("Command line argument parsing");
Benjamin Kramer43c0f482017-06-30 13:21:27 +0000166 ContainsError = false;
Hans Wennborg6ddc6902013-07-27 00:23:45 +0000167
168 unsigned IncludedFlagsBitmask;
169 unsigned ExcludedFlagsBitmask;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +0000170 std::tie(IncludedFlagsBitmask, ExcludedFlagsBitmask) =
Douglas Katzmana67e50c2015-06-26 15:47:46 +0000171 getIncludeExcludeOptionFlagMasks();
Hans Wennborg6ddc6902013-07-27 00:23:45 +0000172
Daniel Dunbar52ed5fe2009-11-19 06:35:06 +0000173 unsigned MissingArgIndex, MissingArgCount;
David Blaikie69a1d8c2015-06-22 22:07:27 +0000174 InputArgList Args =
David Blaikie6d492ad2015-06-21 06:32:36 +0000175 getOpts().ParseArgs(ArgStrings, MissingArgIndex, MissingArgCount,
176 IncludedFlagsBitmask, ExcludedFlagsBitmask);
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +0000177
Daniel Dunbar52ed5fe2009-11-19 06:35:06 +0000178 // Check for missing argument error.
Benjamin Kramer43c0f482017-06-30 13:21:27 +0000179 if (MissingArgCount) {
180 Diag(diag::err_drv_missing_argument)
David Blaikie69a1d8c2015-06-22 22:07:27 +0000181 << Args.getArgString(MissingArgIndex) << MissingArgCount;
Benjamin Kramer43c0f482017-06-30 13:21:27 +0000182 ContainsError |=
183 Diags.getDiagnosticLevel(diag::err_drv_missing_argument,
184 SourceLocation()) > DiagnosticsEngine::Warning;
185 }
Daniel Dunbar65229332009-03-13 11:38:42 +0000186
Daniel Dunbar52ed5fe2009-11-19 06:35:06 +0000187 // Check for unsupported options.
David Blaikie69a1d8c2015-06-22 22:07:27 +0000188 for (const Arg *A : Args) {
Michael J. Spencer66e2b202012-10-19 22:37:06 +0000189 if (A->getOption().hasFlag(options::Unsupported)) {
Brian Gesiak24910762018-01-06 00:25:40 +0000190 unsigned DiagID;
191 auto ArgString = A->getAsString(Args);
192 std::string Nearest;
193 if (getOpts().findNearest(
194 ArgString, Nearest, IncludedFlagsBitmask,
195 ExcludedFlagsBitmask | options::Unsupported) > 1) {
196 DiagID = diag::err_drv_unsupported_opt;
197 Diag(DiagID) << ArgString;
198 } else {
199 DiagID = diag::err_drv_unsupported_opt_with_suggestion;
200 Diag(DiagID) << ArgString << Nearest;
201 }
202 ContainsError |= Diags.getDiagnosticLevel(DiagID, SourceLocation()) >
Benjamin Kramer43c0f482017-06-30 13:21:27 +0000203 DiagnosticsEngine::Warning;
Daniel Dunbard8500f32009-03-22 23:26:43 +0000204 continue;
205 }
Chad Rosierce975d92012-02-22 17:55:22 +0000206
207 // Warn about -mcpu= without an argument.
Douglas Katzmana67e50c2015-06-26 15:47:46 +0000208 if (A->getOption().matches(options::OPT_mcpu_EQ) && A->containsValue("")) {
Benjamin Kramer43c0f482017-06-30 13:21:27 +0000209 Diag(diag::warn_drv_empty_joined_argument) << A->getAsString(Args);
210 ContainsError |= Diags.getDiagnosticLevel(
211 diag::warn_drv_empty_joined_argument,
212 SourceLocation()) > DiagnosticsEngine::Warning;
Chad Rosierce975d92012-02-22 17:55:22 +0000213 }
Daniel Dunbard02cb1d2009-03-05 06:38:47 +0000214 }
215
Benjamin Kramer43c0f482017-06-30 13:21:27 +0000216 for (const Arg *A : Args.filtered(options::OPT_UNKNOWN)) {
Brian Gesiak24910762018-01-06 00:25:40 +0000217 unsigned DiagID;
218 auto ArgString = A->getAsString(Args);
219 std::string Nearest;
220 if (getOpts().findNearest(
221 ArgString, Nearest, IncludedFlagsBitmask, ExcludedFlagsBitmask) > 1) {
222 DiagID = IsCLMode() ? diag::warn_drv_unknown_argument_clang_cl
223 : diag::err_drv_unknown_argument;
224 Diags.Report(DiagID) << ArgString;
225 } else {
226 DiagID = IsCLMode() ? diag::warn_drv_unknown_argument_clang_cl_with_suggestion
227 : diag::err_drv_unknown_argument_with_suggestion;
228 Diags.Report(DiagID) << ArgString << Nearest;
229 }
230 ContainsError |= Diags.getDiagnosticLevel(DiagID, SourceLocation()) >
Benjamin Kramer43c0f482017-06-30 13:21:27 +0000231 DiagnosticsEngine::Warning;
232 }
Rafael Espindola8a2d4962013-09-23 23:55:25 +0000233
Daniel Dunbard02cb1d2009-03-05 06:38:47 +0000234 return Args;
235}
236
Chad Rosier7742b5d2011-07-27 23:36:45 +0000237// Determine which compilation mode we are in. We look for options which
238// affect the phase, starting with the earliest phases, and record which
239// option we used to determine the final phase.
Douglas Katzmana67e50c2015-06-26 15:47:46 +0000240phases::ID Driver::getFinalPhase(const DerivedArgList &DAL,
241 Arg **FinalPhaseArg) const {
Craig Topper92fc2df2014-05-17 16:56:41 +0000242 Arg *PhaseArg = nullptr;
Chad Rosier7742b5d2011-07-27 23:36:45 +0000243 phases::ID FinalPhase;
Eric Christopherf901e852011-08-17 22:59:59 +0000244
Hans Wennborge50cec32014-06-13 20:59:54 +0000245 // -{E,EP,P,M,MM} only run the preprocessor.
Douglas Katzmana67e50c2015-06-26 15:47:46 +0000246 if (CCCIsCPP() || (PhaseArg = DAL.getLastArg(options::OPT_E)) ||
Hans Wennborge50cec32014-06-13 20:59:54 +0000247 (PhaseArg = DAL.getLastArg(options::OPT__SLASH_EP)) ||
Hans Wennborge0053472013-12-20 18:40:46 +0000248 (PhaseArg = DAL.getLastArg(options::OPT_M, options::OPT_MM)) ||
249 (PhaseArg = DAL.getLastArg(options::OPT__SLASH_P))) {
Chad Rosier7742b5d2011-07-27 23:36:45 +0000250 FinalPhase = phases::Preprocess;
Eric Christopherf901e852011-08-17 22:59:59 +0000251
Richard Smithdd4ad3d2016-08-30 19:06:26 +0000252 // --precompile only runs up to precompilation.
253 } else if ((PhaseArg = DAL.getLastArg(options::OPT__precompile))) {
254 FinalPhase = phases::Precompile;
255
Bob Wilson23a55f12014-12-21 07:00:00 +0000256 // -{fsyntax-only,-analyze,emit-ast} only run up to the compiler.
Chad Rosier7742b5d2011-07-27 23:36:45 +0000257 } else if ((PhaseArg = DAL.getLastArg(options::OPT_fsyntax_only)) ||
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +0000258 (PhaseArg = DAL.getLastArg(options::OPT_module_file_info)) ||
Ben Langmuir2cb4a782014-02-05 22:21:15 +0000259 (PhaseArg = DAL.getLastArg(options::OPT_verify_pch)) ||
Chad Rosier7742b5d2011-07-27 23:36:45 +0000260 (PhaseArg = DAL.getLastArg(options::OPT_rewrite_objc)) ||
Fariborz Jahanian73223bb2012-04-02 15:59:19 +0000261 (PhaseArg = DAL.getLastArg(options::OPT_rewrite_legacy_objc)) ||
Ted Kremenekf7639e12012-03-06 20:06:33 +0000262 (PhaseArg = DAL.getLastArg(options::OPT__migrate)) ||
Chad Rosier7742b5d2011-07-27 23:36:45 +0000263 (PhaseArg = DAL.getLastArg(options::OPT__analyze,
Chad Rosier1aeb15a2012-03-06 23:14:35 +0000264 options::OPT__analyze_auto)) ||
Bob Wilson23a55f12014-12-21 07:00:00 +0000265 (PhaseArg = DAL.getLastArg(options::OPT_emit_ast))) {
Chad Rosier7742b5d2011-07-27 23:36:45 +0000266 FinalPhase = phases::Compile;
267
Bob Wilson23a55f12014-12-21 07:00:00 +0000268 // -S only runs up to the backend.
269 } else if ((PhaseArg = DAL.getLastArg(options::OPT_S))) {
270 FinalPhase = phases::Backend;
271
Artem Belevich4242f412015-07-28 21:01:21 +0000272 // -c compilation only runs up to the assembler.
273 } else if ((PhaseArg = DAL.getLastArg(options::OPT_c))) {
Chad Rosier7742b5d2011-07-27 23:36:45 +0000274 FinalPhase = phases::Assemble;
275
276 // Otherwise do everything.
277 } else
278 FinalPhase = phases::Link;
279
280 if (FinalPhaseArg)
281 *FinalPhaseArg = PhaseArg;
282
283 return FinalPhase;
284}
285
David Blaikie0aaa7622017-01-13 17:34:15 +0000286static Arg *MakeInputArg(DerivedArgList &Args, OptTable &Opts,
Hans Wennborged1d0722013-08-13 21:32:29 +0000287 StringRef Value) {
David Blaikie0aaa7622017-01-13 17:34:15 +0000288 Arg *A = new Arg(Opts.getOption(options::OPT_INPUT), Value,
Hans Wennborged1d0722013-08-13 21:32:29 +0000289 Args.getBaseArgs().MakeIndex(Value), Value.data());
Hans Wennborg55362852014-05-02 22:55:30 +0000290 Args.AddSynthesizedArg(A);
Hans Wennborged1d0722013-08-13 21:32:29 +0000291 A->claim();
292 return A;
293}
294
Daniel Dunbar775d4062010-06-11 22:00:26 +0000295DerivedArgList *Driver::TranslateInputArgs(const InputArgList &Args) const {
296 DerivedArgList *DAL = new DerivedArgList(Args);
297
Daniel Dunbar2cc3f172010-09-17 00:45:02 +0000298 bool HasNostdlib = Args.hasArg(options::OPT_nostdlib);
Nirav Daveb0bb6142015-11-24 16:07:21 +0000299 bool HasNodefaultlib = Args.hasArg(options::OPT_nodefaultlibs);
Saleem Abdulrasool688b6bc2014-12-29 19:01:36 +0000300 for (Arg *A : Args) {
Daniel Dunbarfb3d7472010-06-14 21:23:12 +0000301 // Unfortunately, we have to parse some forwarding options (-Xassembler,
302 // -Xlinker, -Xpreprocessor) because we either integrate their functionality
303 // (assembler and preprocessor), or bypass a previous driver ('collect2').
Daniel Dunbar5a9d1832010-06-14 21:37:09 +0000304
305 // Rewrite linker options, to replace --no-demangle with a custom internal
306 // option.
307 if ((A->getOption().matches(options::OPT_Wl_COMMA) ||
308 A->getOption().matches(options::OPT_Xlinker)) &&
309 A->containsValue("--no-demangle")) {
Daniel Dunbarfb3d7472010-06-14 21:23:12 +0000310 // Add the rewritten no-demangle argument.
311 DAL->AddFlagArg(A, Opts->getOption(options::OPT_Z_Xlinker__no_demangle));
312
313 // Add the remaining values as Xlinker arguments.
Benjamin Kramer72e64312015-09-24 14:48:49 +0000314 for (StringRef Val : A->getValues())
Douglas Katzmana34b7bf2015-06-30 19:32:57 +0000315 if (Val != "--no-demangle")
316 DAL->AddSeparateArg(A, Opts->getOption(options::OPT_Xlinker), Val);
Daniel Dunbarfb3d7472010-06-14 21:23:12 +0000317
318 continue;
319 }
320
Daniel Dunbar5a9d1832010-06-14 21:37:09 +0000321 // Rewrite preprocessor options, to replace -Wp,-MD,FOO which is used by
322 // some build systems. We don't try to be complete here because we don't
323 // care to encourage this usage model.
324 if (A->getOption().matches(options::OPT_Wp_COMMA) &&
Richard Smithbd55daf2012-11-01 04:30:05 +0000325 (A->getValue(0) == StringRef("-MD") ||
326 A->getValue(0) == StringRef("-MMD"))) {
Daniel Dunbar3648ba72010-06-15 20:30:18 +0000327 // Rewrite to -MD/-MMD along with -MF.
Richard Smithbd55daf2012-11-01 04:30:05 +0000328 if (A->getValue(0) == StringRef("-MD"))
Daniel Dunbar3648ba72010-06-15 20:30:18 +0000329 DAL->AddFlagArg(A, Opts->getOption(options::OPT_MD));
330 else
331 DAL->AddFlagArg(A, Opts->getOption(options::OPT_MMD));
Michael J. Spencer70d85be2012-11-07 23:37:14 +0000332 if (A->getNumValues() == 2)
333 DAL->AddSeparateArg(A, Opts->getOption(options::OPT_MF),
334 A->getValue(1));
Daniel Dunbar5a9d1832010-06-14 21:37:09 +0000335 continue;
336 }
337
Shantonu Senafeb03b2010-09-17 18:39:08 +0000338 // Rewrite reserved library names.
339 if (A->getOption().matches(options::OPT_l)) {
Richard Smithbd55daf2012-11-01 04:30:05 +0000340 StringRef Value = A->getValue();
Daniel Dunbar2cc3f172010-09-17 00:45:02 +0000341
Shantonu Senafeb03b2010-09-17 18:39:08 +0000342 // Rewrite unless -nostdlib is present.
Nirav Daveb0bb6142015-11-24 16:07:21 +0000343 if (!HasNostdlib && !HasNodefaultlib && Value == "stdc++") {
Douglas Katzmana67e50c2015-06-26 15:47:46 +0000344 DAL->AddFlagArg(A, Opts->getOption(options::OPT_Z_reserved_lib_stdcxx));
Daniel Dunbar2cc3f172010-09-17 00:45:02 +0000345 continue;
346 }
Shantonu Senafeb03b2010-09-17 18:39:08 +0000347
348 // Rewrite unconditionally.
349 if (Value == "cc_kext") {
Douglas Katzmana67e50c2015-06-26 15:47:46 +0000350 DAL->AddFlagArg(A, Opts->getOption(options::OPT_Z_reserved_lib_cckext));
Shantonu Senafeb03b2010-09-17 18:39:08 +0000351 continue;
352 }
Daniel Dunbar2cc3f172010-09-17 00:45:02 +0000353 }
354
Hans Wennborged1d0722013-08-13 21:32:29 +0000355 // Pick up inputs via the -- option.
356 if (A->getOption().matches(options::OPT__DASH_DASH)) {
357 A->claim();
Benjamin Kramer72e64312015-09-24 14:48:49 +0000358 for (StringRef Val : A->getValues())
David Blaikie0aaa7622017-01-13 17:34:15 +0000359 DAL->append(MakeInputArg(*DAL, *Opts, Val));
Hans Wennborged1d0722013-08-13 21:32:29 +0000360 continue;
361 }
362
Saleem Abdulrasool688b6bc2014-12-29 19:01:36 +0000363 DAL->append(A);
Daniel Dunbarfb3d7472010-06-14 21:23:12 +0000364 }
Daniel Dunbar775d4062010-06-11 22:00:26 +0000365
Andrey Turetskiy6a8b91d2016-04-21 10:16:48 +0000366 // Enforce -static if -miamcu is present.
Andrey Turetskiy5fea71c2016-06-29 10:57:17 +0000367 if (Args.hasFlag(options::OPT_miamcu, options::OPT_mno_iamcu, false))
368 DAL->AddFlagArg(0, Opts->getOption(options::OPT_static));
Andrey Turetskiy6a8b91d2016-04-21 10:16:48 +0000369
Douglas Katzmana67e50c2015-06-26 15:47:46 +0000370// Add a default value of -mlinker-version=, if one was given and the user
371// didn't specify one.
Daniel Dunbar628fcf42010-08-12 00:05:12 +0000372#if defined(HOST_LINK_VERSION)
Tim Northover018578c2015-06-12 19:21:35 +0000373 if (!Args.hasArg(options::OPT_mlinker_version_EQ) &&
374 strlen(HOST_LINK_VERSION) > 0) {
Daniel Dunbar628fcf42010-08-12 00:05:12 +0000375 DAL->AddJoinedArg(0, Opts->getOption(options::OPT_mlinker_version_EQ),
376 HOST_LINK_VERSION);
Daniel Dunbarb613ffc2010-08-17 22:32:45 +0000377 DAL->getLastArg(options::OPT_mlinker_version_EQ)->claim();
Daniel Dunbar628fcf42010-08-12 00:05:12 +0000378 }
379#endif
380
Daniel Dunbar775d4062010-06-11 22:00:26 +0000381 return DAL;
382}
383
Artem Belevich959e0542015-07-10 19:47:55 +0000384/// \brief Compute target triple from args.
385///
386/// This routine provides the logic to compute a target triple from various
387/// args passed to the driver and the default triple string.
Andrey Turetskiy6a8b91d2016-04-21 10:16:48 +0000388static llvm::Triple computeTargetTriple(const Driver &D,
389 StringRef DefaultTargetTriple,
Artem Belevich959e0542015-07-10 19:47:55 +0000390 const ArgList &Args,
391 StringRef DarwinArchName = "") {
392 // FIXME: Already done in Compilation *Driver::BuildCompilation
393 if (const Arg *A = Args.getLastArg(options::OPT_target))
394 DefaultTargetTriple = A->getValue();
395
396 llvm::Triple Target(llvm::Triple::normalize(DefaultTargetTriple));
397
398 // Handle Apple-specific options available here.
399 if (Target.isOSBinFormatMachO()) {
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +0000400 // If an explicit Darwin arch name is given, that trumps all.
Artem Belevich959e0542015-07-10 19:47:55 +0000401 if (!DarwinArchName.empty()) {
402 tools::darwin::setTripleTypeForMachOArchName(Target, DarwinArchName);
403 return Target;
404 }
405
406 // Handle the Darwin '-arch' flag.
407 if (Arg *A = Args.getLastArg(options::OPT_arch)) {
408 StringRef ArchName = A->getValue();
409 tools::darwin::setTripleTypeForMachOArchName(Target, ArchName);
410 }
411 }
412
413 // Handle pseudo-target flags '-mlittle-endian'/'-EL' and
414 // '-mbig-endian'/'-EB'.
415 if (Arg *A = Args.getLastArg(options::OPT_mlittle_endian,
416 options::OPT_mbig_endian)) {
417 if (A->getOption().matches(options::OPT_mlittle_endian)) {
418 llvm::Triple LE = Target.getLittleEndianArchVariant();
419 if (LE.getArch() != llvm::Triple::UnknownArch)
420 Target = std::move(LE);
421 } else {
422 llvm::Triple BE = Target.getBigEndianArchVariant();
423 if (BE.getArch() != llvm::Triple::UnknownArch)
424 Target = std::move(BE);
425 }
426 }
427
428 // Skip further flag support on OSes which don't support '-m32' or '-m64'.
Douglas Katzman15a63ed2015-08-12 18:36:12 +0000429 if (Target.getArch() == llvm::Triple::tce ||
430 Target.getOS() == llvm::Triple::Minix)
Artem Belevich959e0542015-07-10 19:47:55 +0000431 return Target;
432
433 // Handle pseudo-target flags '-m64', '-mx32', '-m32' and '-m16'.
Andrey Turetskiy6a8b91d2016-04-21 10:16:48 +0000434 Arg *A = Args.getLastArg(options::OPT_m64, options::OPT_mx32,
435 options::OPT_m32, options::OPT_m16);
436 if (A) {
Artem Belevich959e0542015-07-10 19:47:55 +0000437 llvm::Triple::ArchType AT = llvm::Triple::UnknownArch;
438
439 if (A->getOption().matches(options::OPT_m64)) {
440 AT = Target.get64BitArchVariant().getArch();
441 if (Target.getEnvironment() == llvm::Triple::GNUX32)
442 Target.setEnvironment(llvm::Triple::GNU);
443 } else if (A->getOption().matches(options::OPT_mx32) &&
444 Target.get64BitArchVariant().getArch() == llvm::Triple::x86_64) {
445 AT = llvm::Triple::x86_64;
446 Target.setEnvironment(llvm::Triple::GNUX32);
447 } else if (A->getOption().matches(options::OPT_m32)) {
448 AT = Target.get32BitArchVariant().getArch();
449 if (Target.getEnvironment() == llvm::Triple::GNUX32)
450 Target.setEnvironment(llvm::Triple::GNU);
451 } else if (A->getOption().matches(options::OPT_m16) &&
452 Target.get32BitArchVariant().getArch() == llvm::Triple::x86) {
453 AT = llvm::Triple::x86;
454 Target.setEnvironment(llvm::Triple::CODE16);
455 }
456
457 if (AT != llvm::Triple::UnknownArch && AT != Target.getArch())
458 Target.setArch(AT);
459 }
460
Andrey Turetskiy6a8b91d2016-04-21 10:16:48 +0000461 // Handle -miamcu flag.
Andrey Turetskiy5fea71c2016-06-29 10:57:17 +0000462 if (Args.hasFlag(options::OPT_miamcu, options::OPT_mno_iamcu, false)) {
463 if (Target.get32BitArchVariant().getArch() != llvm::Triple::x86)
464 D.Diag(diag::err_drv_unsupported_opt_for_target) << "-miamcu"
465 << Target.str();
Andrey Turetskiy6a8b91d2016-04-21 10:16:48 +0000466
Andrey Turetskiy5fea71c2016-06-29 10:57:17 +0000467 if (A && !A->getOption().matches(options::OPT_m32))
468 D.Diag(diag::err_drv_argument_not_allowed_with)
469 << "-miamcu" << A->getBaseArg().getAsString(Args);
Andrey Turetskiy6a8b91d2016-04-21 10:16:48 +0000470
Andrey Turetskiy5fea71c2016-06-29 10:57:17 +0000471 Target.setArch(llvm::Triple::x86);
472 Target.setArchName("i586");
473 Target.setEnvironment(llvm::Triple::UnknownEnvironment);
474 Target.setEnvironmentName("");
475 Target.setOS(llvm::Triple::ELFIAMCU);
476 Target.setVendor(llvm::Triple::UnknownVendor);
477 Target.setVendorName("intel");
Andrey Turetskiy6a8b91d2016-04-21 10:16:48 +0000478 }
479
Artem Belevich959e0542015-07-10 19:47:55 +0000480 return Target;
481}
482
Teresa Johnson945bc502015-10-15 20:35:53 +0000483// \brief Parse the LTO options and record the type of LTO compilation
484// based on which -f(no-)?lto(=.*)? option occurs last.
485void Driver::setLTOMode(const llvm::opt::ArgList &Args) {
486 LTOMode = LTOK_None;
487 if (!Args.hasFlag(options::OPT_flto, options::OPT_flto_EQ,
488 options::OPT_fno_lto, false))
489 return;
490
491 StringRef LTOName("full");
492
493 const Arg *A = Args.getLastArg(options::OPT_flto_EQ);
Teresa Johnson6ef80dc2015-11-02 18:03:12 +0000494 if (A)
495 LTOName = A->getValue();
Teresa Johnson945bc502015-10-15 20:35:53 +0000496
497 LTOMode = llvm::StringSwitch<LTOKind>(LTOName)
498 .Case("full", LTOK_Full)
499 .Case("thin", LTOK_Thin)
500 .Default(LTOK_Unknown);
501
502 if (LTOMode == LTOK_Unknown) {
503 assert(A);
504 Diag(diag::err_drv_unsupported_option_argument) << A->getOption().getName()
505 << A->getValue();
506 }
507}
508
Samuel Antao39f9da22016-10-27 16:38:05 +0000509/// Compute the desired OpenMP runtime from the flags provided.
510Driver::OpenMPRuntimeKind Driver::getOpenMPRuntime(const ArgList &Args) const {
511 StringRef RuntimeName(CLANG_DEFAULT_OPENMP_RUNTIME);
512
513 const Arg *A = Args.getLastArg(options::OPT_fopenmp_EQ);
514 if (A)
515 RuntimeName = A->getValue();
516
517 auto RT = llvm::StringSwitch<OpenMPRuntimeKind>(RuntimeName)
518 .Case("libomp", OMPRT_OMP)
519 .Case("libgomp", OMPRT_GOMP)
520 .Case("libiomp5", OMPRT_IOMP5)
521 .Default(OMPRT_Unknown);
522
523 if (RT == OMPRT_Unknown) {
524 if (A)
525 Diag(diag::err_drv_unsupported_option_argument)
526 << A->getOption().getName() << A->getValue();
527 else
528 // FIXME: We could use a nicer diagnostic here.
529 Diag(diag::err_drv_unsupported_opt) << "-fopenmp";
530 }
531
532 return RT;
533}
534
Samuel Antaoc1ffba52016-06-13 18:10:57 +0000535void Driver::CreateOffloadingDeviceToolChains(Compilation &C,
536 InputList &Inputs) {
537
538 //
539 // CUDA
540 //
541 // We need to generate a CUDA toolchain if any of the inputs has a CUDA type.
542 if (llvm::any_of(Inputs, [](std::pair<types::ID, const llvm::opt::Arg *> &I) {
543 return types::isCuda(I.first);
544 })) {
Justin Lebar66c4fd72016-11-18 00:41:22 +0000545 const ToolChain *HostTC = C.getSingleOffloadToolChain<Action::OFK_Host>();
546 const llvm::Triple &HostTriple = HostTC->getTriple();
547 llvm::Triple CudaTriple(HostTriple.isArch64Bit() ? "nvptx64-nvidia-cuda"
548 : "nvptx-nvidia-cuda");
549 // Use the CUDA and host triples as the key into the ToolChains map, because
550 // the device toolchain we create depends on both.
David Blaikie6ad71012017-01-13 18:53:43 +0000551 auto &CudaTC = ToolChains[CudaTriple.str() + "/" + HostTriple.str()];
Justin Lebar66c4fd72016-11-18 00:41:22 +0000552 if (!CudaTC) {
David Blaikie6ad71012017-01-13 18:53:43 +0000553 CudaTC = llvm::make_unique<toolchains::CudaToolChain>(
Gheorghe-Teodor Bercea2c926932017-08-08 14:33:05 +0000554 *this, CudaTriple, *HostTC, C.getInputArgs(), Action::OFK_Cuda);
Justin Lebar66c4fd72016-11-18 00:41:22 +0000555 }
David Blaikie6ad71012017-01-13 18:53:43 +0000556 C.addOffloadDeviceToolChain(CudaTC.get(), Action::OFK_Cuda);
Samuel Antaoc1ffba52016-06-13 18:10:57 +0000557 }
558
559 //
Samuel Antao39f9da22016-10-27 16:38:05 +0000560 // OpenMP
561 //
562 // We need to generate an OpenMP toolchain if the user specified targets with
563 // the -fopenmp-targets option.
564 if (Arg *OpenMPTargets =
565 C.getInputArgs().getLastArg(options::OPT_fopenmp_targets_EQ)) {
566 if (OpenMPTargets->getNumValues()) {
567 // We expect that -fopenmp-targets is always used in conjunction with the
568 // option -fopenmp specifying a valid runtime with offloading support,
569 // i.e. libomp or libiomp.
570 bool HasValidOpenMPRuntime = C.getInputArgs().hasFlag(
571 options::OPT_fopenmp, options::OPT_fopenmp_EQ,
572 options::OPT_fno_openmp, false);
573 if (HasValidOpenMPRuntime) {
574 OpenMPRuntimeKind OpenMPKind = getOpenMPRuntime(C.getInputArgs());
575 HasValidOpenMPRuntime =
576 OpenMPKind == OMPRT_OMP || OpenMPKind == OMPRT_IOMP5;
577 }
578
579 if (HasValidOpenMPRuntime) {
580 llvm::StringMap<const char *> FoundNormalizedTriples;
581 for (const char *Val : OpenMPTargets->getValues()) {
582 llvm::Triple TT(Val);
583 std::string NormalizedName = TT.normalize();
584
585 // Make sure we don't have a duplicate triple.
586 auto Duplicate = FoundNormalizedTriples.find(NormalizedName);
587 if (Duplicate != FoundNormalizedTriples.end()) {
588 Diag(clang::diag::warn_drv_omp_offload_target_duplicate)
589 << Val << Duplicate->second;
590 continue;
591 }
592
593 // Store the current triple so that we can check for duplicates in the
594 // following iterations.
595 FoundNormalizedTriples[NormalizedName] = Val;
596
597 // If the specified target is invalid, emit a diagnostic.
598 if (TT.getArch() == llvm::Triple::UnknownArch)
599 Diag(clang::diag::err_drv_invalid_omp_target) << Val;
600 else {
Gheorghe-Teodor Bercea6a5df722017-07-06 16:08:15 +0000601 const ToolChain *TC;
602 // CUDA toolchains have to be selected differently. They pair host
603 // and device in their implementation.
604 if (TT.isNVPTX()) {
605 const ToolChain *HostTC =
606 C.getSingleOffloadToolChain<Action::OFK_Host>();
607 assert(HostTC && "Host toolchain should be always defined.");
608 auto &CudaTC =
Gheorghe-Teodor Bercea52898432017-08-09 01:02:19 +0000609 ToolChains[TT.str() + "/" + HostTC->getTriple().normalize()];
Gheorghe-Teodor Bercea6a5df722017-07-06 16:08:15 +0000610 if (!CudaTC)
611 CudaTC = llvm::make_unique<toolchains::CudaToolChain>(
Gheorghe-Teodor Bercea2c926932017-08-08 14:33:05 +0000612 *this, TT, *HostTC, C.getInputArgs(), Action::OFK_OpenMP);
Gheorghe-Teodor Bercea6a5df722017-07-06 16:08:15 +0000613 TC = CudaTC.get();
614 } else
615 TC = &getToolChain(C.getInputArgs(), TT);
616 C.addOffloadDeviceToolChain(TC, Action::OFK_OpenMP);
Samuel Antao39f9da22016-10-27 16:38:05 +0000617 }
618 }
619 } else
620 Diag(clang::diag::err_drv_expecting_fopenmp_with_fopenmp_targets);
621 } else
622 Diag(clang::diag::warn_drv_empty_joined_argument)
623 << OpenMPTargets->getAsString(C.getInputArgs());
624 }
625
626 //
Samuel Antaoc1ffba52016-06-13 18:10:57 +0000627 // TODO: Add support for other offloading programming models here.
628 //
Samuel Antaoc1ffba52016-06-13 18:10:57 +0000629}
630
Serge Pavlov208ac652018-01-01 13:27:01 +0000631/// Looks the given directories for the specified file.
632///
633/// \param[out] FilePath File path, if the file was found.
634/// \param[in] Dirs Directories used for the search.
635/// \param[in] FileName Name of the file to search for.
636/// \return True if file was found.
637///
638/// Looks for file specified by FileName sequentially in directories specified
639/// by Dirs.
640///
641static bool searchForFile(SmallVectorImpl<char> &FilePath,
642 ArrayRef<std::string> Dirs,
643 StringRef FileName) {
644 SmallString<128> WPath;
645 for (const StringRef &Dir : Dirs) {
646 if (Dir.empty())
647 continue;
648 WPath.clear();
649 llvm::sys::path::append(WPath, Dir, FileName);
650 llvm::sys::path::native(WPath);
651 if (llvm::sys::fs::is_regular_file(WPath)) {
652 FilePath = std::move(WPath);
653 return true;
654 }
655 }
656 return false;
657}
658
659bool Driver::readConfigFile(StringRef FileName) {
660 // Try reading the given file.
661 SmallVector<const char *, 32> NewCfgArgs;
662 if (!llvm::cl::readConfigFile(FileName, Saver, NewCfgArgs)) {
663 Diag(diag::err_drv_cannot_read_config_file) << FileName;
664 return true;
665 }
666
667 // Read options from config file.
668 llvm::SmallString<128> CfgFileName(FileName);
669 llvm::sys::path::native(CfgFileName);
670 ConfigFile = CfgFileName.str();
671 bool ContainErrors;
672 CfgOptions = llvm::make_unique<InputArgList>(
673 ParseArgStrings(NewCfgArgs, ContainErrors));
674 if (ContainErrors) {
675 CfgOptions.reset();
676 return true;
677 }
678
679 if (CfgOptions->hasArg(options::OPT_config)) {
680 CfgOptions.reset();
681 Diag(diag::err_drv_nested_config_file);
682 return true;
683 }
684
685 // Claim all arguments that come from a configuration file so that the driver
686 // does not warn on any that is unused.
687 for (Arg *A : *CfgOptions)
688 A->claim();
689 return false;
690}
691
692bool Driver::loadConfigFile() {
693 std::string CfgFileName;
694 bool FileSpecifiedExplicitly = false;
695
696 // Process options that change search path for config files.
697 if (CLOptions) {
698 if (CLOptions->hasArg(options::OPT_config_system_dir_EQ)) {
699 SmallString<128> CfgDir;
700 CfgDir.append(
701 CLOptions->getLastArgValue(options::OPT_config_system_dir_EQ));
702 if (!CfgDir.empty()) {
Sam McCall296d8322018-01-02 09:35:10 +0000703 if (llvm::sys::fs::make_absolute(CfgDir).value() != 0)
Serge Pavlov208ac652018-01-01 13:27:01 +0000704 SystemConfigDir.clear();
705 else
706 SystemConfigDir = std::string(CfgDir.begin(), CfgDir.end());
707 }
708 }
709 if (CLOptions->hasArg(options::OPT_config_user_dir_EQ)) {
710 SmallString<128> CfgDir;
711 CfgDir.append(
712 CLOptions->getLastArgValue(options::OPT_config_user_dir_EQ));
713 if (!CfgDir.empty()) {
Sam McCall296d8322018-01-02 09:35:10 +0000714 if (llvm::sys::fs::make_absolute(CfgDir).value() != 0)
Serge Pavlov208ac652018-01-01 13:27:01 +0000715 UserConfigDir.clear();
716 else
717 UserConfigDir = std::string(CfgDir.begin(), CfgDir.end());
718 }
719 }
720 }
721
722 // First try to find config file specified in command line.
723 if (CLOptions) {
724 std::vector<std::string> ConfigFiles =
725 CLOptions->getAllArgValues(options::OPT_config);
726 if (ConfigFiles.size() > 1) {
727 Diag(diag::err_drv_duplicate_config);
728 return true;
729 }
730
731 if (!ConfigFiles.empty()) {
732 CfgFileName = ConfigFiles.front();
733 assert(!CfgFileName.empty());
734
735 // If argument contains directory separator, treat it as a path to
736 // configuration file.
737 if (llvm::sys::path::has_parent_path(CfgFileName)) {
738 SmallString<128> CfgFilePath;
739 if (llvm::sys::path::is_relative(CfgFileName))
740 llvm::sys::fs::current_path(CfgFilePath);
741 llvm::sys::path::append(CfgFilePath, CfgFileName);
742 if (!llvm::sys::fs::is_regular_file(CfgFilePath)) {
743 Diag(diag::err_drv_config_file_not_exist) << CfgFilePath;
744 return true;
745 }
746 return readConfigFile(CfgFilePath);
747 }
748
749 FileSpecifiedExplicitly = true;
750 }
751 }
752
753 // If config file is not specified explicitly, try to deduce configuration
754 // from executable name. For instance, an executable 'armv7l-clang' will
755 // search for config file 'armv7l-clang.cfg'.
756 if (CfgFileName.empty() && !ClangNameParts.TargetPrefix.empty())
757 CfgFileName = ClangNameParts.TargetPrefix + '-' + ClangNameParts.ModeSuffix;
758
759 if (CfgFileName.empty())
760 return false;
761
762 // Determine architecture part of the file name, if it is present.
763 StringRef CfgFileArch = CfgFileName;
764 size_t ArchPrefixLen = CfgFileArch.find('-');
765 if (ArchPrefixLen == StringRef::npos)
766 ArchPrefixLen = CfgFileArch.size();
767 llvm::Triple CfgTriple;
768 CfgFileArch = CfgFileArch.take_front(ArchPrefixLen);
769 CfgTriple = llvm::Triple(llvm::Triple::normalize(CfgFileArch));
770 if (CfgTriple.getArch() == llvm::Triple::ArchType::UnknownArch)
771 ArchPrefixLen = 0;
772
773 if (!StringRef(CfgFileName).endswith(".cfg"))
774 CfgFileName += ".cfg";
775
776 // If config file starts with architecture name and command line options
777 // redefine architecture (with options like -m32 -LE etc), try finding new
778 // config file with that architecture.
779 SmallString<128> FixedConfigFile;
780 size_t FixedArchPrefixLen = 0;
781 if (ArchPrefixLen) {
782 // Get architecture name from config file name like 'i386.cfg' or
783 // 'armv7l-clang.cfg'.
784 // Check if command line options changes effective triple.
785 llvm::Triple EffectiveTriple = computeTargetTriple(*this,
786 CfgTriple.getTriple(), *CLOptions);
787 if (CfgTriple.getArch() != EffectiveTriple.getArch()) {
788 FixedConfigFile = EffectiveTriple.getArchName();
789 FixedArchPrefixLen = FixedConfigFile.size();
790 // Append the rest of original file name so that file name transforms
791 // like: i386-clang.cfg -> x86_64-clang.cfg.
792 if (ArchPrefixLen < CfgFileName.size())
793 FixedConfigFile += CfgFileName.substr(ArchPrefixLen);
794 }
795 }
796
797 // Prepare list of directories where config file is searched for.
798 SmallVector<std::string, 3> CfgFileSearchDirs;
799 CfgFileSearchDirs.push_back(UserConfigDir);
800 CfgFileSearchDirs.push_back(SystemConfigDir);
801 CfgFileSearchDirs.push_back(Dir);
802
803 // Try to find config file. First try file with corrected architecture.
804 llvm::SmallString<128> CfgFilePath;
805 if (!FixedConfigFile.empty()) {
806 if (searchForFile(CfgFilePath, CfgFileSearchDirs, FixedConfigFile))
807 return readConfigFile(CfgFilePath);
808 // If 'x86_64-clang.cfg' was not found, try 'x86_64.cfg'.
809 FixedConfigFile.resize(FixedArchPrefixLen);
810 FixedConfigFile.append(".cfg");
811 if (searchForFile(CfgFilePath, CfgFileSearchDirs, FixedConfigFile))
812 return readConfigFile(CfgFilePath);
813 }
814
815 // Then try original file name.
816 if (searchForFile(CfgFilePath, CfgFileSearchDirs, CfgFileName))
817 return readConfigFile(CfgFilePath);
818
819 // Finally try removing driver mode part: 'x86_64-clang.cfg' -> 'x86_64.cfg'.
820 if (!ClangNameParts.ModeSuffix.empty() &&
821 !ClangNameParts.TargetPrefix.empty()) {
822 CfgFileName.assign(ClangNameParts.TargetPrefix);
823 CfgFileName.append(".cfg");
824 if (searchForFile(CfgFilePath, CfgFileSearchDirs, CfgFileName))
825 return readConfigFile(CfgFilePath);
826 }
827
828 // Report error but only if config file was specified explicitly, by option
829 // --config. If it was deduced from executable name, it is not an error.
830 if (FileSpecifiedExplicitly) {
831 Diag(diag::err_drv_config_file_not_found) << CfgFileName;
832 for (const std::string &SearchDir : CfgFileSearchDirs)
833 if (!SearchDir.empty())
834 Diag(diag::note_drv_config_file_searched_in) << SearchDir;
835 return true;
836 }
837
838 return false;
839}
840
Chris Lattner54b16772011-07-23 17:14:25 +0000841Compilation *Driver::BuildCompilation(ArrayRef<const char *> ArgList) {
Daniel Dunbar2608c542009-03-18 01:38:48 +0000842 llvm::PrettyStackTraceString CrashInfo("Compilation construction");
843
Eric Christopherf901e852011-08-17 22:59:59 +0000844 // FIXME: Handle environment options which affect driver behavior, somewhere
Bill Wendlingadbeb9f2012-03-12 21:24:57 +0000845 // (client?). GCC_EXEC_PREFIX, LPATH, CC_PRINT_OPTIONS.
Chad Rosier82301162011-09-14 00:47:55 +0000846
David Majnemer85c25b42016-07-24 17:44:03 +0000847 if (Optional<std::string> CompilerPathValue =
848 llvm::sys::Process::GetEnv("COMPILER_PATH")) {
849 StringRef CompilerPath = *CompilerPathValue;
Chad Rosier82301162011-09-14 00:47:55 +0000850 while (!CompilerPath.empty()) {
Douglas Katzmana67e50c2015-06-26 15:47:46 +0000851 std::pair<StringRef, StringRef> Split =
852 CompilerPath.split(llvm::sys::EnvPathSeparator);
Chad Rosier82301162011-09-14 00:47:55 +0000853 PrefixDirs.push_back(Split.first);
854 CompilerPath = Split.second;
855 }
856 }
Daniel Dunbar5e0f6af2009-03-13 00:51:18 +0000857
Hans Wennborg70850d82013-07-18 20:29:38 +0000858 // We look for the driver mode option early, because the mode can affect
859 // how other options are parsed.
Zachary Turneraff19c32016-08-12 17:47:52 +0000860 ParseDriverMode(ClangExecutable, ArgList.slice(1));
Hans Wennborg70850d82013-07-18 20:29:38 +0000861
Daniel Dunbar5e0f6af2009-03-13 00:51:18 +0000862 // FIXME: What are we going to do with -V and -b?
863
Serge Pavlov208ac652018-01-01 13:27:01 +0000864 // Arguments specified in command line.
865 bool ContainsError;
866 CLOptions = llvm::make_unique<InputArgList>(
867 ParseArgStrings(ArgList.slice(1), ContainsError));
868
869 // Try parsing configuration file.
870 if (!ContainsError)
871 ContainsError = loadConfigFile();
872 bool HasConfigFile = !ContainsError && (CfgOptions.get() != nullptr);
873
874 // All arguments, from both config file and command line.
875 InputArgList Args = std::move(HasConfigFile ? std::move(*CfgOptions)
876 : std::move(*CLOptions));
877 if (HasConfigFile)
878 for (auto *Opt : *CLOptions) {
879 const Arg *BaseArg = &Opt->getBaseArg();
880 if (BaseArg == Opt)
881 BaseArg = nullptr;
882 Arg *Copy = new llvm::opt::Arg(Opt->getOption(), Opt->getSpelling(),
883 Args.size(), BaseArg);
884 Copy->getValues() = Opt->getValues();
885 if (Opt->isClaimed())
886 Copy->claim();
887 Args.append(Copy);
888 }
889
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +0000890 // FIXME: This stuff needs to go into the Compilation, not the driver.
Douglas Katzmanb7e8ef02015-06-25 19:37:41 +0000891 bool CCCPrintPhases;
Daniel Dunbard02cb1d2009-03-05 06:38:47 +0000892
Filipe Cabecinhas136f35e2015-07-18 06:35:24 +0000893 // Silence driver warnings if requested
894 Diags.setIgnoreAllWarnings(Args.hasArg(options::OPT_w));
895
Rafael Espindola59ae7992009-12-07 18:28:29 +0000896 // -no-canonical-prefixes is used very early in main.
David Blaikie69a1d8c2015-06-22 22:07:27 +0000897 Args.ClaimAllArgs(options::OPT_no_canonical_prefixes);
Rafael Espindola59ae7992009-12-07 18:28:29 +0000898
Daniel Dunbar926f81f2010-08-02 02:38:03 +0000899 // Ignore -pipe.
David Blaikie69a1d8c2015-06-22 22:07:27 +0000900 Args.ClaimAllArgs(options::OPT_pipe);
Daniel Dunbar926f81f2010-08-02 02:38:03 +0000901
Daniel Dunbaracd69572009-12-04 21:55:23 +0000902 // Extract -ccc args.
Daniel Dunbaree66cf22009-03-10 20:52:46 +0000903 //
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +0000904 // FIXME: We need to figure out where this behavior should live. Most of it
905 // should be outside in the client; the parts that aren't should have proper
906 // options, either by introducing new ones or by overloading gcc ones like -V
907 // or -b.
Douglas Katzmanb7e8ef02015-06-25 19:37:41 +0000908 CCCPrintPhases = Args.hasArg(options::OPT_ccc_print_phases);
David Blaikie69a1d8c2015-06-22 22:07:27 +0000909 CCCPrintBindings = Args.hasArg(options::OPT_ccc_print_bindings);
910 if (const Arg *A = Args.getLastArg(options::OPT_ccc_gcc_name))
Richard Smithbd55daf2012-11-01 04:30:05 +0000911 CCCGenericGCCName = A->getValue();
David Blaikie69a1d8c2015-06-22 22:07:27 +0000912 CCCUsePCH =
913 Args.hasFlag(options::OPT_ccc_pch_is_pch, options::OPT_ccc_pch_is_pth);
Bruno Cardoso Lopes52dfe712017-04-12 21:46:20 +0000914 GenReproducer = Args.hasFlag(options::OPT_gen_reproducer,
915 options::OPT_fno_crash_diagnostics,
916 !!::getenv("FORCE_CLANG_DIAGNOSTICS_CRASH"));
Joerg Sonnenberger17d75512012-02-22 19:15:16 +0000917 // FIXME: DefaultTargetTriple is used by the target-prefixed calls to as/ld
918 // and getToolChain is const.
Hans Wennborg2e274592013-08-13 23:38:57 +0000919 if (IsCLMode()) {
Hans Wennborg73609a02014-03-28 01:19:04 +0000920 // clang-cl targets MSVC-style Win32.
Hans Wennborg2e274592013-08-13 23:38:57 +0000921 llvm::Triple T(DefaultTargetTriple);
Hans Wennborg9d9ce7a2014-03-28 20:49:28 +0000922 T.setOS(llvm::Triple::Win32);
Hans Wennborg0f0e8d62015-09-18 17:11:50 +0000923 T.setVendor(llvm::Triple::PC);
Hans Wennborg9d9ce7a2014-03-28 20:49:28 +0000924 T.setEnvironment(llvm::Triple::MSVC);
Oleg Ranevskyy80523182017-08-31 20:31:30 +0000925 T.setObjectFormat(llvm::Triple::COFF);
Hans Wennborg2e274592013-08-13 23:38:57 +0000926 DefaultTargetTriple = T.str();
927 }
David Blaikie69a1d8c2015-06-22 22:07:27 +0000928 if (const Arg *A = Args.getLastArg(options::OPT_target))
Richard Smithbd55daf2012-11-01 04:30:05 +0000929 DefaultTargetTriple = A->getValue();
David Blaikie69a1d8c2015-06-22 22:07:27 +0000930 if (const Arg *A = Args.getLastArg(options::OPT_ccc_install_dir))
Richard Smithbd55daf2012-11-01 04:30:05 +0000931 Dir = InstalledDir = A->getValue();
David Blaikie69a1d8c2015-06-22 22:07:27 +0000932 for (const Arg *A : Args.filtered(options::OPT_B)) {
Benjamin Kramer1a648d12011-02-08 20:31:42 +0000933 A->claim();
Richard Smithbd55daf2012-11-01 04:30:05 +0000934 PrefixDirs.push_back(A->getValue(0));
Benjamin Kramer1a648d12011-02-08 20:31:42 +0000935 }
David Blaikie69a1d8c2015-06-22 22:07:27 +0000936 if (const Arg *A = Args.getLastArg(options::OPT__sysroot_EQ))
Richard Smithbd55daf2012-11-01 04:30:05 +0000937 SysRoot = A->getValue();
David Blaikie69a1d8c2015-06-22 22:07:27 +0000938 if (const Arg *A = Args.getLastArg(options::OPT__dyld_prefix_EQ))
Peter Collingbourne9d9e1fc2013-05-27 21:40:20 +0000939 DyldPrefix = A->getValue();
Daniel Dunbaree66cf22009-03-10 20:52:46 +0000940
David Blaikie69a1d8c2015-06-22 22:07:27 +0000941 if (const Arg *A = Args.getLastArg(options::OPT_resource_dir))
Bob Wilsona20a1da2013-03-23 05:17:59 +0000942 ResourceDir = A->getValue();
Jim Grosbach061dabf2013-03-12 20:17:58 +0000943
David Blaikie69a1d8c2015-06-22 22:07:27 +0000944 if (const Arg *A = Args.getLastArg(options::OPT_save_temps_EQ)) {
Reid Kleckner68eb60b2015-02-02 22:41:48 +0000945 SaveTemps = llvm::StringSwitch<SaveTempsMode>(A->getValue())
946 .Case("cwd", SaveTempsCwd)
947 .Case("obj", SaveTempsObj)
948 .Default(SaveTempsCwd);
949 }
950
Steven Wu1257cd82016-05-18 17:04:52 +0000951 setLTOMode(Args);
952
Steven Wu844ab6a2016-11-16 06:06:44 +0000953 // Process -fembed-bitcode= flags.
954 if (Arg *A = Args.getLastArg(options::OPT_fembed_bitcode_EQ)) {
955 StringRef Name = A->getValue();
956 unsigned Model = llvm::StringSwitch<unsigned>(Name)
957 .Case("off", EmbedNone)
958 .Case("all", EmbedBitcode)
959 .Case("bitcode", EmbedBitcode)
960 .Case("marker", EmbedMarker)
961 .Default(~0U);
962 if (Model == ~0U) {
963 Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args)
964 << Name;
965 } else
966 BitcodeEmbed = static_cast<BitcodeEmbedMode>(Model);
Steven Wu574b0f22016-03-01 01:07:58 +0000967 }
968
David Blaikie69a1d8c2015-06-22 22:07:27 +0000969 std::unique_ptr<llvm::opt::InputArgList> UArgs =
970 llvm::make_unique<InputArgList>(std::move(Args));
971
Daniel Dunbar775d4062010-06-11 22:00:26 +0000972 // Perform the default argument translations.
David Blaikie69a1d8c2015-06-22 22:07:27 +0000973 DerivedArgList *TranslatedArgs = TranslateInputArgs(*UArgs);
Daniel Dunbar775d4062010-06-11 22:00:26 +0000974
Chandler Carruthcb916192012-01-25 08:49:21 +0000975 // Owned by the host.
Andrey Turetskiy6a8b91d2016-04-21 10:16:48 +0000976 const ToolChain &TC = getToolChain(
977 *UArgs, computeTargetTriple(*this, DefaultTargetTriple, *UArgs));
Chandler Carruthcb916192012-01-25 08:49:21 +0000978
Daniel Dunbar3ce436d2009-03-16 06:42:30 +0000979 // The compilation takes ownership of Args.
Benjamin Kramer43c0f482017-06-30 13:21:27 +0000980 Compilation *C = new Compilation(*this, TC, UArgs.release(), TranslatedArgs,
981 ContainsError);
Daniel Dunbarf0eddb82009-03-18 02:55:38 +0000982
Daniel Dunbarf0eddb82009-03-18 02:55:38 +0000983 if (!HandleImmediateArgs(*C))
984 return C;
985
Chad Rosierecdede82011-08-12 22:08:57 +0000986 // Construct the list of inputs.
987 InputList Inputs;
Hans Wennborged1d0722013-08-13 21:32:29 +0000988 BuildInputs(C->getDefaultToolChain(), *TranslatedArgs, Inputs);
Chad Rosierecdede82011-08-12 22:08:57 +0000989
Samuel Antaoc1ffba52016-06-13 18:10:57 +0000990 // Populate the tool chains for the offloading devices, if any.
991 CreateOffloadingDeviceToolChains(*C, Inputs);
Justin Lebar0e450a52016-03-30 23:30:25 +0000992
Chandler Carruth7f1417f2012-01-24 10:43:44 +0000993 // Construct the list of abstract actions to perform for this compilation. On
Tim Northover157d9112014-01-16 08:48:16 +0000994 // MachO targets this uses the driver-driver and universal actions.
995 if (TC.getTriple().isOSBinFormatMachO())
Artem Belevich5e2a3ec2015-11-17 22:28:40 +0000996 BuildUniversalActions(*C, C->getDefaultToolChain(), Inputs);
Daniel Dunbarf0eddb82009-03-18 02:55:38 +0000997 else
Justin Lebar0f3474c2016-02-11 02:00:50 +0000998 BuildActions(*C, C->getArgs(), Inputs, C->getActions());
Daniel Dunbarf0eddb82009-03-18 02:55:38 +0000999
Douglas Katzmanb7e8ef02015-06-25 19:37:41 +00001000 if (CCCPrintPhases) {
Daniel Dunbareb843be2009-03-18 03:13:20 +00001001 PrintActions(*C);
Daniel Dunbarf0eddb82009-03-18 02:55:38 +00001002 return C;
1003 }
1004
1005 BuildJobs(*C);
Daniel Dunbaradc91e62009-03-15 01:38:15 +00001006
1007 return C;
Daniel Dunbaree66cf22009-03-10 20:52:46 +00001008}
1009
Justin Bognered9cbe02015-07-09 06:58:31 +00001010static void printArgList(raw_ostream &OS, const llvm::opt::ArgList &Args) {
1011 llvm::opt::ArgStringList ASL;
1012 for (const auto *A : Args)
1013 A->render(Args, ASL);
1014
1015 for (auto I = ASL.begin(), E = ASL.end(); I != E; ++I) {
1016 if (I != ASL.begin())
1017 OS << ' ';
1018 Command::printArg(OS, *I, true);
1019 }
1020 OS << '\n';
1021}
1022
Bruno Cardoso Lopes02681c42016-11-17 21:41:22 +00001023bool Driver::getCrashDiagnosticFile(StringRef ReproCrashFilename,
1024 SmallString<128> &CrashDiagDir) {
1025 using namespace llvm::sys;
1026 assert(llvm::Triple(llvm::sys::getProcessTriple()).isOSDarwin() &&
1027 "Only knows about .crash files on Darwin");
1028
1029 // The .crash file can be found on at ~/Library/Logs/DiagnosticReports/
1030 // (or /Library/Logs/DiagnosticReports for root) and has the filename pattern
1031 // clang-<VERSION>_<YYYY-MM-DD-HHMMSS>_<hostname>.crash.
1032 path::home_directory(CrashDiagDir);
1033 if (CrashDiagDir.startswith("/var/root"))
1034 CrashDiagDir = "/";
1035 path::append(CrashDiagDir, "Library/Logs/DiagnosticReports");
1036 int PID =
1037#if LLVM_ON_UNIX
1038 getpid();
1039#else
1040 0;
1041#endif
1042 std::error_code EC;
1043 fs::file_status FileStatus;
1044 TimePoint<> LastAccessTime;
1045 SmallString<128> CrashFilePath;
1046 // Lookup the .crash files and get the one generated by a subprocess spawned
1047 // by this driver invocation.
1048 for (fs::directory_iterator File(CrashDiagDir, EC), FileEnd;
1049 File != FileEnd && !EC; File.increment(EC)) {
1050 StringRef FileName = path::filename(File->path());
1051 if (!FileName.startswith(Name))
1052 continue;
1053 if (fs::status(File->path(), FileStatus))
1054 continue;
1055 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> CrashFile =
1056 llvm::MemoryBuffer::getFile(File->path());
1057 if (!CrashFile)
1058 continue;
1059 // The first line should start with "Process:", otherwise this isn't a real
1060 // .crash file.
1061 StringRef Data = CrashFile.get()->getBuffer();
1062 if (!Data.startswith("Process:"))
1063 continue;
1064 // Parse parent process pid line, e.g: "Parent Process: clang-4.0 [79141]"
1065 size_t ParentProcPos = Data.find("Parent Process:");
1066 if (ParentProcPos == StringRef::npos)
1067 continue;
1068 size_t LineEnd = Data.find_first_of("\n", ParentProcPos);
1069 if (LineEnd == StringRef::npos)
1070 continue;
1071 StringRef ParentProcess = Data.slice(ParentProcPos+15, LineEnd).trim();
1072 int OpenBracket = -1, CloseBracket = -1;
1073 for (size_t i = 0, e = ParentProcess.size(); i < e; ++i) {
1074 if (ParentProcess[i] == '[')
1075 OpenBracket = i;
1076 if (ParentProcess[i] == ']')
1077 CloseBracket = i;
1078 }
1079 // Extract the parent process PID from the .crash file and check whether
1080 // it matches this driver invocation pid.
1081 int CrashPID;
1082 if (OpenBracket < 0 || CloseBracket < 0 ||
1083 ParentProcess.slice(OpenBracket + 1, CloseBracket)
1084 .getAsInteger(10, CrashPID) || CrashPID != PID) {
1085 continue;
1086 }
1087
1088 // Found a .crash file matching the driver pid. To avoid getting an older
1089 // and misleading crash file, continue looking for the most recent.
1090 // FIXME: the driver can dispatch multiple cc1 invocations, leading to
1091 // multiple crashes poiting to the same parent process. Since the driver
1092 // does not collect pid information for the dispatched invocation there's
1093 // currently no way to distinguish among them.
1094 const auto FileAccessTime = FileStatus.getLastModificationTime();
1095 if (FileAccessTime > LastAccessTime) {
1096 CrashFilePath.assign(File->path());
1097 LastAccessTime = FileAccessTime;
1098 }
1099 }
1100
1101 // If found, copy it over to the location of other reproducer files.
1102 if (!CrashFilePath.empty()) {
1103 EC = fs::copy_file(CrashFilePath, ReproCrashFilename);
1104 if (EC)
1105 return false;
1106 return true;
1107 }
1108
1109 return false;
1110}
1111
Eric Christopherf901e852011-08-17 22:59:59 +00001112// When clang crashes, produce diagnostic information including the fully
1113// preprocessed source file(s). Request that the developer attach the
Chad Rosierbe10f982011-08-02 17:58:04 +00001114// diagnostic information to a bug report.
Alex Lorenz045c5142018-04-07 00:03:27 +00001115void Driver::generateCompilationDiagnostics(
1116 Compilation &C, const Command &FailingCommand,
1117 StringRef AdditionalInformation, CompilationDiagnosticReport *Report) {
Chad Rosier877c0a22012-02-22 00:30:39 +00001118 if (C.getArgs().hasArg(options::OPT_fno_crash_diagnostics))
Chad Rosier62135492012-07-09 17:31:28 +00001119 return;
Chad Rosierbee5a1d2012-03-07 00:30:40 +00001120
Chad Rosierdbf46a12013-02-01 18:30:26 +00001121 // Don't try to generate diagnostics for link or dsymutil jobs.
Justin Bognere1a33d12014-10-20 21:02:05 +00001122 if (FailingCommand.getCreator().isLinkJob() ||
1123 FailingCommand.getCreator().isDsymutilJob())
Chad Rosier877c0a22012-02-22 00:30:39 +00001124 return;
1125
Chad Rosier8179f112012-06-19 17:51:34 +00001126 // Print the version of the compiler.
1127 PrintVersion(C, llvm::errs());
1128
Chad Rosierbe10f982011-08-02 17:58:04 +00001129 Diag(clang::diag::note_drv_command_failed_diag_msg)
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001130 << "PLEASE submit a bug report to " BUG_REPORT_URL " and include the "
1131 "crash backtrace, preprocessed source, and associated run script.";
Chad Rosierbe10f982011-08-02 17:58:04 +00001132
1133 // Suppress driver output and emit preprocessor output to temp file.
Hans Wennborg70850d82013-07-18 20:29:38 +00001134 Mode = CPPMode;
Chad Rosierbe10f982011-08-02 17:58:04 +00001135 CCGenDiagnostics = true;
1136
Chad Rosiercdb008d2011-11-02 21:29:05 +00001137 // Save the original job command(s).
Justin Bogner25645152014-10-21 17:24:44 +00001138 Command Cmd = FailingCommand;
Chad Rosiercdb008d2011-11-02 21:29:05 +00001139
Richard Smith5bb4cdf2012-12-20 02:22:15 +00001140 // Keep track of whether we produce any errors while trying to produce
1141 // preprocessed sources.
1142 DiagnosticErrorTrap Trap(Diags);
1143
1144 // Suppress tool output.
Chad Rosierbe10f982011-08-02 17:58:04 +00001145 C.initCompilationForDiagnostics();
Chad Rosierecdede82011-08-12 22:08:57 +00001146
1147 // Construct the list of inputs.
1148 InputList Inputs;
1149 BuildInputs(C.getDefaultToolChain(), C.getArgs(), Inputs);
Chad Rosierbe10f982011-08-02 17:58:04 +00001150
Chad Rosier4f81fc22011-08-12 23:30:05 +00001151 for (InputList::iterator it = Inputs.begin(), ie = Inputs.end(); it != ie;) {
Chad Rosierd57133d2011-08-18 00:22:25 +00001152 bool IgnoreInput = false;
1153
1154 // Ignore input from stdin or any inputs that cannot be preprocessed.
Paul Robinsonf44157d2014-04-28 22:24:44 +00001155 // Check type first as not all linker inputs have a value.
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001156 if (types::getPreprocessedType(it->first) == types::TY_INVALID) {
Paul Robinsonf44157d2014-04-28 22:24:44 +00001157 IgnoreInput = true;
1158 } else if (!strcmp(it->second->getValue(), "-")) {
Chad Rosierd57133d2011-08-18 00:22:25 +00001159 Diag(clang::diag::note_drv_command_failed_diag_msg)
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001160 << "Error generating preprocessed source(s) - "
1161 "ignoring input from stdin.";
Chad Rosierd57133d2011-08-18 00:22:25 +00001162 IgnoreInput = true;
Chad Rosierd57133d2011-08-18 00:22:25 +00001163 }
1164
1165 if (IgnoreInput) {
Chad Rosier4f81fc22011-08-12 23:30:05 +00001166 it = Inputs.erase(it);
1167 ie = Inputs.end();
Chad Rosier6fdf38b2011-08-17 23:08:45 +00001168 } else {
Chad Rosier4f81fc22011-08-12 23:30:05 +00001169 ++it;
Chad Rosier6fdf38b2011-08-17 23:08:45 +00001170 }
Chad Rosier4f81fc22011-08-12 23:30:05 +00001171 }
Chad Rosierd57133d2011-08-18 00:22:25 +00001172
Chad Rosierc5103c32013-01-29 23:57:10 +00001173 if (Inputs.empty()) {
1174 Diag(clang::diag::note_drv_command_failed_diag_msg)
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001175 << "Error generating preprocessed source(s) - "
1176 "no preprocessable inputs.";
Chad Rosierc5103c32013-01-29 23:57:10 +00001177 return;
1178 }
1179
Chad Rosiere75ef402011-09-06 23:52:36 +00001180 // Don't attempt to generate preprocessed files if multiple -arch options are
Chad Rosier636d2832012-02-13 18:16:28 +00001181 // used, unless they're all duplicates.
1182 llvm::StringSet<> ArchNames;
Saleem Abdulrasool688b6bc2014-12-29 19:01:36 +00001183 for (const Arg *A : C.getArgs()) {
Chad Rosiere75ef402011-09-06 23:52:36 +00001184 if (A->getOption().matches(options::OPT_arch)) {
Richard Smithbd55daf2012-11-01 04:30:05 +00001185 StringRef ArchName = A->getValue();
Chad Rosier636d2832012-02-13 18:16:28 +00001186 ArchNames.insert(ArchName);
Chad Rosiere75ef402011-09-06 23:52:36 +00001187 }
1188 }
Chad Rosier636d2832012-02-13 18:16:28 +00001189 if (ArchNames.size() > 1) {
1190 Diag(clang::diag::note_drv_command_failed_diag_msg)
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001191 << "Error generating preprocessed source(s) - cannot generate "
1192 "preprocessed source with multiple -arch options.";
Chad Rosier636d2832012-02-13 18:16:28 +00001193 return;
1194 }
Chad Rosiere75ef402011-09-06 23:52:36 +00001195
Chandler Carruth7f1417f2012-01-24 10:43:44 +00001196 // Construct the list of abstract actions to perform for this compilation. On
1197 // Darwin OSes this uses the driver-driver and builds universal actions.
Chandler Carruthcb916192012-01-25 08:49:21 +00001198 const ToolChain &TC = C.getDefaultToolChain();
Tim Northover157d9112014-01-16 08:48:16 +00001199 if (TC.getTriple().isOSBinFormatMachO())
Artem Belevich5e2a3ec2015-11-17 22:28:40 +00001200 BuildUniversalActions(C, TC, Inputs);
Chad Rosierbe10f982011-08-02 17:58:04 +00001201 else
Justin Lebar0f3474c2016-02-11 02:00:50 +00001202 BuildActions(C, C.getArgs(), Inputs, C.getActions());
Chad Rosierbe10f982011-08-02 17:58:04 +00001203
1204 BuildJobs(C);
1205
1206 // If there were errors building the compilation, quit now.
Richard Smith5bb4cdf2012-12-20 02:22:15 +00001207 if (Trap.hasErrorOccurred()) {
Chad Rosierbe10f982011-08-02 17:58:04 +00001208 Diag(clang::diag::note_drv_command_failed_diag_msg)
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001209 << "Error generating preprocessed source(s).";
Chad Rosierbe10f982011-08-02 17:58:04 +00001210 return;
1211 }
1212
1213 // Generate preprocessed output.
Chad Rosierdd60e092013-01-29 20:15:05 +00001214 SmallVector<std::pair<int, const Command *>, 4> FailingCommands;
Justin Bogner0cd92482015-07-02 22:52:08 +00001215 C.ExecuteJobs(C.getJobs(), FailingCommands);
Chad Rosierbe10f982011-08-02 17:58:04 +00001216
Justin Bognerbc89b182014-10-20 21:20:27 +00001217 // If any of the preprocessing commands failed, clean up and exit.
1218 if (!FailingCommands.empty()) {
Reid Kleckner68eb60b2015-02-02 22:41:48 +00001219 if (!isSaveTempsEnabled())
Chad Rosierbe10f982011-08-02 17:58:04 +00001220 C.CleanupFileList(C.getTempFiles(), true);
1221
1222 Diag(clang::diag::note_drv_command_failed_diag_msg)
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001223 << "Error generating preprocessed source(s).";
Justin Bognerbc89b182014-10-20 21:20:27 +00001224 return;
Chad Rosierbe10f982011-08-02 17:58:04 +00001225 }
Justin Bognerbc89b182014-10-20 21:20:27 +00001226
Justin Bognerc1fdf7f2014-10-20 21:47:56 +00001227 const ArgStringList &TempFiles = C.getTempFiles();
1228 if (TempFiles.empty()) {
1229 Diag(clang::diag::note_drv_command_failed_diag_msg)
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001230 << "Error generating preprocessed source(s).";
Justin Bognerc1fdf7f2014-10-20 21:47:56 +00001231 return;
1232 }
1233
Justin Bognerbc89b182014-10-20 21:20:27 +00001234 Diag(clang::diag::note_drv_command_failed_diag_msg)
1235 << "\n********************\n\n"
1236 "PLEASE ATTACH THE FOLLOWING FILES TO THE BUG REPORT:\n"
1237 "Preprocessed source(s) and associated run script(s) are located at:";
Justin Bognerbc89b182014-10-20 21:20:27 +00001238
Justin Bogner659ecc32014-10-20 22:47:23 +00001239 SmallString<128> VFS;
Bruno Cardoso Lopes02681c42016-11-17 21:41:22 +00001240 SmallString<128> ReproCrashFilename;
Justin Bogner659ecc32014-10-20 22:47:23 +00001241 for (const char *TempFile : TempFiles) {
Justin Bognerc1fdf7f2014-10-20 21:47:56 +00001242 Diag(clang::diag::note_drv_command_failed_diag_msg) << TempFile;
Alex Lorenz045c5142018-04-07 00:03:27 +00001243 if (Report)
1244 Report->TemporaryFiles.push_back(TempFile);
Bruno Cardoso Lopes02681c42016-11-17 21:41:22 +00001245 if (ReproCrashFilename.empty()) {
1246 ReproCrashFilename = TempFile;
1247 llvm::sys::path::replace_extension(ReproCrashFilename, ".crash");
1248 }
Justin Bogner659ecc32014-10-20 22:47:23 +00001249 if (StringRef(TempFile).endswith(".cache")) {
1250 // In some cases (modules) we'll dump extra data to help with reproducing
1251 // the crash into a directory next to the output.
1252 VFS = llvm::sys::path::filename(TempFile);
1253 llvm::sys::path::append(VFS, "vfs", "vfs.yaml");
1254 }
1255 }
Justin Bognerc1fdf7f2014-10-20 21:47:56 +00001256
1257 // Assume associated files are based off of the first temporary file.
Justin Bogner25645152014-10-21 17:24:44 +00001258 CrashReportInfo CrashInfo(TempFiles[0], VFS);
Justin Bognerc1fdf7f2014-10-20 21:47:56 +00001259
Justin Bogner25645152014-10-21 17:24:44 +00001260 std::string Script = CrashInfo.Filename.rsplit('.').first.str() + ".sh";
Justin Bognerc1fdf7f2014-10-20 21:47:56 +00001261 std::error_code EC;
Justin Bognerc1fdf7f2014-10-20 21:47:56 +00001262 llvm::raw_fd_ostream ScriptOS(Script, EC, llvm::sys::fs::F_Excl);
1263 if (EC) {
1264 Diag(clang::diag::note_drv_command_failed_diag_msg)
1265 << "Error generating run script: " + Script + " " + EC.message();
1266 } else {
Justin Bogner42220ed2015-03-12 00:14:35 +00001267 ScriptOS << "# Crash reproducer for " << getClangFullVersion() << "\n"
Justin Bognered9cbe02015-07-09 06:58:31 +00001268 << "# Driver args: ";
1269 printArgList(ScriptOS, C.getInputArgs());
1270 ScriptOS << "# Original command: ";
Justin Bogner42220ed2015-03-12 00:14:35 +00001271 Cmd.Print(ScriptOS, "\n", /*Quote=*/true);
Justin Bogner33bdbc62014-10-21 18:03:08 +00001272 Cmd.Print(ScriptOS, "\n", /*Quote=*/true, &CrashInfo);
Alex Lorenz045c5142018-04-07 00:03:27 +00001273 if (!AdditionalInformation.empty())
1274 ScriptOS << "\n# Additional information: " << AdditionalInformation
1275 << "\n";
1276 if (Report)
1277 Report->TemporaryFiles.push_back(Script);
Justin Bognerc1fdf7f2014-10-20 21:47:56 +00001278 Diag(clang::diag::note_drv_command_failed_diag_msg) << Script;
Justin Bognerbc89b182014-10-20 21:20:27 +00001279 }
Saleem Abdulrasool3661a822015-01-12 02:33:09 +00001280
Bruno Cardoso Lopes02681c42016-11-17 21:41:22 +00001281 // On darwin, provide information about the .crash diagnostic report.
1282 if (llvm::Triple(llvm::sys::getProcessTriple()).isOSDarwin()) {
1283 SmallString<128> CrashDiagDir;
1284 if (getCrashDiagnosticFile(ReproCrashFilename, CrashDiagDir)) {
1285 Diag(clang::diag::note_drv_command_failed_diag_msg)
1286 << ReproCrashFilename.str();
1287 } else { // Suggest a directory for the user to look for .crash files.
1288 llvm::sys::path::append(CrashDiagDir, Name);
1289 CrashDiagDir += "_<YYYY-MM-DD-HHMMSS>_<hostname>.crash";
1290 Diag(clang::diag::note_drv_command_failed_diag_msg)
1291 << "Crash backtrace is located in";
1292 Diag(clang::diag::note_drv_command_failed_diag_msg)
1293 << CrashDiagDir.str();
1294 Diag(clang::diag::note_drv_command_failed_diag_msg)
1295 << "(choose the .crash file that corresponds to your crash)";
1296 }
1297 }
1298
Saleem Abdulrasool3661a822015-01-12 02:33:09 +00001299 for (const auto &A : C.getArgs().filtered(options::OPT_frewrite_map_file,
1300 options::OPT_frewrite_map_file_EQ))
1301 Diag(clang::diag::note_drv_command_failed_diag_msg) << A->getValue();
1302
Justin Bognerbc89b182014-10-20 21:20:27 +00001303 Diag(clang::diag::note_drv_command_failed_diag_msg)
1304 << "\n\n********************";
Chad Rosierbe10f982011-08-02 17:58:04 +00001305}
1306
Justin Bogner0cd92482015-07-02 22:52:08 +00001307void Driver::setUpResponseFiles(Compilation &C, Command &Cmd) {
Oleg Ranevskyycd516372016-01-05 19:54:39 +00001308 // Since commandLineFitsWithinSystemLimits() may underestimate system's capacity
Reid Kleckner0290c9c2014-09-15 17:45:39 +00001309 // if the tool does not support response files, there is a chance/ that things
1310 // will just work without a response file, so we silently just skip it.
Justin Bogner0cd92482015-07-02 22:52:08 +00001311 if (Cmd.getCreator().getResponseFilesSupport() == Tool::RF_None ||
Oleg Ranevskyycd516372016-01-05 19:54:39 +00001312 llvm::sys::commandLineFitsWithinSystemLimits(Cmd.getExecutable(), Cmd.getArguments()))
Reid Kleckner0290c9c2014-09-15 17:45:39 +00001313 return;
1314
1315 std::string TmpName = GetTemporaryPath("response", "txt");
Malcolm Parsonsf76f6502016-11-02 10:39:27 +00001316 Cmd.setResponseFile(C.addTempFile(C.getArgs().MakeArgString(TmpName)));
Reid Kleckner0290c9c2014-09-15 17:45:39 +00001317}
1318
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001319int Driver::ExecuteCompilation(
1320 Compilation &C,
1321 SmallVectorImpl<std::pair<int, const Command *>> &FailingCommands) {
Daniel Dunbar38bfda62009-07-01 20:03:04 +00001322 // Just print if -### was present.
1323 if (C.getArgs().hasArg(options::OPT__HASH_HASH_HASH)) {
Hans Wennborgb212b342013-09-12 18:23:34 +00001324 C.getJobs().Print(llvm::errs(), "\n", true);
Daniel Dunbar38bfda62009-07-01 20:03:04 +00001325 return 0;
1326 }
1327
1328 // If there were errors building the compilation, quit now.
Chad Rosierbe10f982011-08-02 17:58:04 +00001329 if (Diags.hasErrorOccurred())
Daniel Dunbar38bfda62009-07-01 20:03:04 +00001330 return 1;
1331
Reid Kleckner0290c9c2014-09-15 17:45:39 +00001332 // Set up response file names for each command, if necessary
Justin Bogner0cd92482015-07-02 22:52:08 +00001333 for (auto &Job : C.getJobs())
1334 setUpResponseFiles(C, Job);
Reid Kleckner0290c9c2014-09-15 17:45:39 +00001335
Justin Bogner0cd92482015-07-02 22:52:08 +00001336 C.ExecuteJobs(C.getJobs(), FailingCommands);
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001337
Daniel Dunbar38bfda62009-07-01 20:03:04 +00001338 // Remove temp files.
1339 C.CleanupFileList(C.getTempFiles());
1340
Daniel Dunbar07494792010-05-22 00:37:20 +00001341 // If the command succeeded, we are done.
Chad Rosierdd60e092013-01-29 20:15:05 +00001342 if (FailingCommands.empty())
1343 return 0;
Daniel Dunbar07494792010-05-22 00:37:20 +00001344
Chad Rosierdd60e092013-01-29 20:15:05 +00001345 // Otherwise, remove result files and print extra information about abnormal
1346 // failures.
Douglas Katzman6bbffc42015-06-25 18:51:37 +00001347 for (const auto &CmdPair : FailingCommands) {
1348 int Res = CmdPair.first;
1349 const Command *FailingCommand = CmdPair.second;
Daniel Dunbar38bfda62009-07-01 20:03:04 +00001350
Chad Rosierdd60e092013-01-29 20:15:05 +00001351 // Remove result files if we're not saving temps.
Reid Kleckner68eb60b2015-02-02 22:41:48 +00001352 if (!isSaveTempsEnabled()) {
Chad Rosierdd60e092013-01-29 20:15:05 +00001353 const JobAction *JA = cast<JobAction>(&FailingCommand->getSource());
1354 C.CleanupFileMap(C.getResultFiles(), JA, true);
1355
1356 // Failure result files are valid unless we crashed.
1357 if (Res < 0)
1358 C.CleanupFileMap(C.getFailureResultFiles(), JA, true);
1359 }
1360
1361 // Print extra information about abnormal failures, if possible.
1362 //
1363 // This is ad-hoc, but we don't want to be excessively noisy. If the result
Justin Bogner5aaf2e72014-06-26 20:59:36 +00001364 // status was 1, assume the command failed normally. In particular, if it
Chad Rosierdd60e092013-01-29 20:15:05 +00001365 // was the compiler then assume it gave a reasonable error code. Failures
1366 // in other tools are less common, and they generally have worse
1367 // diagnostics, so always print the diagnostic there.
1368 const Tool &FailingTool = FailingCommand->getCreator();
1369
1370 if (!FailingCommand->getCreator().hasGoodDiagnostics() || Res != 1) {
1371 // FIXME: See FIXME above regarding result code interpretation.
1372 if (Res < 0)
1373 Diag(clang::diag::err_drv_command_signalled)
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001374 << FailingTool.getShortName();
Chad Rosierdd60e092013-01-29 20:15:05 +00001375 else
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001376 Diag(clang::diag::err_drv_command_failed) << FailingTool.getShortName()
1377 << Res;
Chad Rosierdd60e092013-01-29 20:15:05 +00001378 }
Peter Collingbourne119cfaa2011-11-21 00:01:05 +00001379 }
Chad Rosierdd60e092013-01-29 20:15:05 +00001380 return 0;
Daniel Dunbar38bfda62009-07-01 20:03:04 +00001381}
1382
Daniel Dunbara7b5e212009-04-15 16:34:29 +00001383void Driver::PrintHelp(bool ShowHidden) const {
Hans Wennborg6ddc6902013-07-27 00:23:45 +00001384 unsigned IncludedFlagsBitmask;
1385 unsigned ExcludedFlagsBitmask;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00001386 std::tie(IncludedFlagsBitmask, ExcludedFlagsBitmask) =
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001387 getIncludeExcludeOptionFlagMasks();
Hans Wennborg6ddc6902013-07-27 00:23:45 +00001388
1389 ExcludedFlagsBitmask |= options::NoDriverOption;
1390 if (!ShowHidden)
1391 ExcludedFlagsBitmask |= HelpHidden;
1392
1393 getOpts().PrintHelp(llvm::outs(), Name.c_str(), DriverTitle.c_str(),
George Rimar5dbfa4e2017-07-26 09:10:17 +00001394 IncludedFlagsBitmask, ExcludedFlagsBitmask,
1395 /*ShowAllAliases=*/false);
Daniel Dunbar7c925282009-03-31 21:38:17 +00001396}
1397
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001398void Driver::PrintVersion(const Compilation &C, raw_ostream &OS) const {
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001399 // FIXME: The following handlers should use a callback mechanism, we don't
1400 // know what the client would like to do.
Ted Kremenek4c0df3d2010-01-23 02:11:34 +00001401 OS << getClangFullVersion() << '\n';
Daniel Dunbarb10248802009-03-26 16:09:13 +00001402 const ToolChain &TC = C.getDefaultToolChain();
Daniel Dunbar08e41d62009-07-21 20:06:58 +00001403 OS << "Target: " << TC.getTripleString() << '\n';
Daniel Dunbar10978e42009-06-16 23:32:58 +00001404
1405 // Print the threading model.
Jonathan Roelofsb140a102014-10-03 21:57:44 +00001406 if (Arg *A = C.getArgs().getLastArg(options::OPT_mthread_model)) {
1407 // Don't print if the ToolChain would have barfed on it already
1408 if (TC.isThreadModelSupported(A->getValue()))
1409 OS << "Thread model: " << A->getValue();
1410 } else
1411 OS << "Thread model: " << TC.getThreadModel();
1412 OS << '\n';
Chandler Carruth9ade6a92015-08-05 17:07:33 +00001413
1414 // Print out the install directory.
1415 OS << "InstalledDir: " << InstalledDir << '\n';
Serge Pavlov208ac652018-01-01 13:27:01 +00001416
1417 // If configuration file was used, print its path.
1418 if (!ConfigFile.empty())
1419 OS << "Configuration file: " << ConfigFile << '\n';
Daniel Dunbar5e0f6af2009-03-13 00:51:18 +00001420}
1421
Chris Lattner86ed5b02010-05-05 05:53:24 +00001422/// PrintDiagnosticCategories - Implement the --print-diagnostic-categories
1423/// option.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001424static void PrintDiagnosticCategories(raw_ostream &OS) {
Argyrios Kyrtzidis0e37afa2011-05-25 05:05:01 +00001425 // Skip the empty category.
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001426 for (unsigned i = 1, max = DiagnosticIDs::getNumberOfCategories(); i != max;
1427 ++i)
Argyrios Kyrtzidis0e37afa2011-05-25 05:05:01 +00001428 OS << i << ',' << DiagnosticIDs::getCategoryNameFromID(i) << '\n';
Chris Lattner86ed5b02010-05-05 05:53:24 +00001429}
1430
Yuka Takahashi41789e42018-03-05 08:54:20 +00001431void Driver::HandleAutocompletions(StringRef PassedFlags) const {
Yuka Takahashi503da8f2018-03-05 09:01:31 +00001432 if (PassedFlags == "")
1433 return;
Yuka Takahashi1a895202017-08-29 17:46:46 +00001434 // Print out all options that start with a given argument. This is used for
1435 // shell autocompletion.
1436 std::vector<std::string> SuggestedCompletions;
Yuka Takahashi41789e42018-03-05 08:54:20 +00001437 std::vector<std::string> Flags;
Yuka Takahashi1a895202017-08-29 17:46:46 +00001438
1439 unsigned short DisableFlags =
1440 options::NoDriverOption | options::Unsupported | options::Ignored;
Yuka Takahashi41789e42018-03-05 08:54:20 +00001441
1442 // Parse PassedFlags by "," as all the command-line flags are passed to this
1443 // function separated by ","
1444 StringRef TargetFlags = PassedFlags;
1445 while (TargetFlags != "") {
1446 StringRef CurFlag;
1447 std::tie(CurFlag, TargetFlags) = TargetFlags.split(",");
1448 Flags.push_back(std::string(CurFlag));
Yuka Takahashi1a895202017-08-29 17:46:46 +00001449 }
1450
Yuka Takahashi41789e42018-03-05 08:54:20 +00001451 // We want to show cc1-only options only when clang is invoked with -cc1 or
1452 // -Xclang.
Yuka Takahashi503da8f2018-03-05 09:01:31 +00001453 if (std::find(Flags.begin(), Flags.end(), "-Xclang") != Flags.end() ||
1454 std::find(Flags.begin(), Flags.end(), "-cc1") != Flags.end())
Yuka Takahashi41789e42018-03-05 08:54:20 +00001455 DisableFlags &= ~options::NoDriverOption;
1456
1457 StringRef Cur;
1458 Cur = Flags.at(Flags.size() - 1);
1459 StringRef Prev;
1460 if (Flags.size() >= 2) {
1461 Prev = Flags.at(Flags.size() - 2);
1462 SuggestedCompletions = Opts->suggestValueCompletions(Prev, Cur);
1463 }
1464
1465 if (SuggestedCompletions.empty())
1466 SuggestedCompletions = Opts->suggestValueCompletions(Cur, "");
1467
1468 if (SuggestedCompletions.empty()) {
Yuka Takahashi1a895202017-08-29 17:46:46 +00001469 // If the flag is in the form of "--autocomplete=-foo",
1470 // we were requested to print out all option names that start with "-foo".
1471 // For example, "--autocomplete=-fsyn" is expanded to "-fsyntax-only".
Yuka Takahashi41789e42018-03-05 08:54:20 +00001472 SuggestedCompletions = Opts->findByPrefix(Cur, DisableFlags);
Yuka Takahashi1a895202017-08-29 17:46:46 +00001473
1474 // We have to query the -W flags manually as they're not in the OptTable.
1475 // TODO: Find a good way to add them to OptTable instead and them remove
1476 // this code.
1477 for (StringRef S : DiagnosticIDs::getDiagnosticFlags())
Yuka Takahashi41789e42018-03-05 08:54:20 +00001478 if (S.startswith(Cur))
Yuka Takahashi1a895202017-08-29 17:46:46 +00001479 SuggestedCompletions.push_back(S);
Yuka Takahashi1a895202017-08-29 17:46:46 +00001480 }
1481
1482 // Sort the autocomplete candidates so that shells print them out in a
1483 // deterministic order. We could sort in any way, but we chose
1484 // case-insensitive sorting for consistency with the -help option
1485 // which prints out options in the case-insensitive alphabetical order.
Mandeep Singh Grangc205d8c2018-03-27 16:50:00 +00001486 llvm::sort(SuggestedCompletions.begin(), SuggestedCompletions.end(),
1487 [](StringRef A, StringRef B) {
1488 if (int X = A.compare_lower(B))
1489 return X < 0;
1490 return A.compare(B) > 0;
Mandeep Singh Grang8f54ae12017-11-20 18:49:14 +00001491 });
Yuka Takahashi1a895202017-08-29 17:46:46 +00001492
1493 llvm::outs() << llvm::join(SuggestedCompletions, "\n") << '\n';
1494}
1495
Daniel Dunbarf0eddb82009-03-18 02:55:38 +00001496bool Driver::HandleImmediateArgs(const Compilation &C) {
Daniel Dunbar18974bd2010-06-11 22:00:19 +00001497 // The order these options are handled in gcc is all over the place, but we
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001498 // don't expect inconsistencies w.r.t. that to matter in practice.
Daniel Dunbar7c925282009-03-31 21:38:17 +00001499
Daniel Dunbar1b09e042010-09-17 02:47:28 +00001500 if (C.getArgs().hasArg(options::OPT_dumpmachine)) {
1501 llvm::outs() << C.getDefaultToolChain().getTripleString() << '\n';
1502 return false;
1503 }
1504
Daniel Dunbara9bbcfa2009-04-04 05:17:38 +00001505 if (C.getArgs().hasArg(options::OPT_dumpversion)) {
Daniel Dunbare26e5002011-01-12 00:43:47 +00001506 // Since -dumpversion is only implemented for pedantic GCC compatibility, we
1507 // return an answer which matches our definition of __VERSION__.
1508 //
1509 // If we want to return a more correct answer some day, then we should
1510 // introduce a non-pedantically GCC compatible mode to Clang in which we
1511 // provide sensible definitions for -dumpversion, __VERSION__, etc.
1512 llvm::outs() << "4.2.1\n";
Daniel Dunbara9bbcfa2009-04-04 05:17:38 +00001513 return false;
1514 }
Daniel Dunbarfb3d7472010-06-14 21:23:12 +00001515
Chris Lattner86ed5b02010-05-05 05:53:24 +00001516 if (C.getArgs().hasArg(options::OPT__print_diagnostic_categories)) {
1517 PrintDiagnosticCategories(llvm::outs());
1518 return false;
1519 }
Daniel Dunbara9bbcfa2009-04-04 05:17:38 +00001520
James Molloya3c85b82012-05-01 14:57:16 +00001521 if (C.getArgs().hasArg(options::OPT_help) ||
Daniel Dunbara7b5e212009-04-15 16:34:29 +00001522 C.getArgs().hasArg(options::OPT__help_hidden)) {
1523 PrintHelp(C.getArgs().hasArg(options::OPT__help_hidden));
Daniel Dunbar7c925282009-03-31 21:38:17 +00001524 return false;
1525 }
1526
Daniel Dunbarb0006ae2009-04-02 15:05:41 +00001527 if (C.getArgs().hasArg(options::OPT__version)) {
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001528 // Follow gcc behavior and use stdout for --version and stderr for -v.
Daniel Dunbar08e41d62009-07-21 20:06:58 +00001529 PrintVersion(C, llvm::outs());
Daniel Dunbarb0006ae2009-04-02 15:05:41 +00001530 return false;
1531 }
1532
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001533 if (C.getArgs().hasArg(options::OPT_v) ||
Daniel Dunbarf0eddb82009-03-18 02:55:38 +00001534 C.getArgs().hasArg(options::OPT__HASH_HASH_HASH)) {
Daniel Dunbar08e41d62009-07-21 20:06:58 +00001535 PrintVersion(C, llvm::errs());
Daniel Dunbar5e0f6af2009-03-13 00:51:18 +00001536 SuppressMissingInputWarning = true;
1537 }
1538
Serge Pavlov208ac652018-01-01 13:27:01 +00001539 if (C.getArgs().hasArg(options::OPT_v)) {
1540 if (!SystemConfigDir.empty())
1541 llvm::errs() << "System configuration file directory: "
1542 << SystemConfigDir << "\n";
1543 if (!UserConfigDir.empty())
1544 llvm::errs() << "User configuration file directory: "
1545 << UserConfigDir << "\n";
1546 }
1547
Daniel Dunbarf0eddb82009-03-18 02:55:38 +00001548 const ToolChain &TC = C.getDefaultToolChain();
Chandler Carruth0ae39aa2013-07-30 17:57:09 +00001549
1550 if (C.getArgs().hasArg(options::OPT_v))
1551 TC.printVerboseInfo(llvm::errs());
1552
Meador Inge51208a32017-04-04 21:46:50 +00001553 if (C.getArgs().hasArg(options::OPT_print_resource_dir)) {
Meador Ingea9113952017-04-05 22:27:20 +00001554 llvm::outs() << ResourceDir << '\n';
Meador Inge51208a32017-04-04 21:46:50 +00001555 return false;
1556 }
1557
Daniel Dunbard972e222009-03-20 04:37:21 +00001558 if (C.getArgs().hasArg(options::OPT_print_search_dirs)) {
1559 llvm::outs() << "programs: =";
Douglas Katzman51fe7bf2015-06-23 22:43:50 +00001560 bool separator = false;
1561 for (const std::string &Path : TC.getProgramPaths()) {
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001562 if (separator)
1563 llvm::outs() << ':';
Douglas Katzman51fe7bf2015-06-23 22:43:50 +00001564 llvm::outs() << Path;
1565 separator = true;
Daniel Dunbard972e222009-03-20 04:37:21 +00001566 }
1567 llvm::outs() << "\n";
Peter Collingbournefa9771f2011-09-06 02:08:31 +00001568 llvm::outs() << "libraries: =" << ResourceDir;
Joerg Sonnenberger9c3e69b2011-07-16 10:50:05 +00001569
Sebastian Pop980920a2012-04-16 04:16:43 +00001570 StringRef sysroot = C.getSysRoot();
Joerg Sonnenberger9c3e69b2011-07-16 10:50:05 +00001571
Douglas Katzman51fe7bf2015-06-23 22:43:50 +00001572 for (const std::string &Path : TC.getFilePaths()) {
1573 // Always print a separator. ResourceDir was the first item shown.
Peter Collingbournefa9771f2011-09-06 02:08:31 +00001574 llvm::outs() << ':';
Douglas Katzman51fe7bf2015-06-23 22:43:50 +00001575 // Interpretation of leading '=' is needed only for NetBSD.
1576 if (Path[0] == '=')
Douglas Katzman26eabf62015-06-24 15:10:30 +00001577 llvm::outs() << sysroot << Path.substr(1);
Joerg Sonnenberger9c3e69b2011-07-16 10:50:05 +00001578 else
Douglas Katzman51fe7bf2015-06-23 22:43:50 +00001579 llvm::outs() << Path;
Daniel Dunbard972e222009-03-20 04:37:21 +00001580 }
1581 llvm::outs() << "\n";
Daniel Dunbar7c925282009-03-31 21:38:17 +00001582 return false;
Daniel Dunbard972e222009-03-20 04:37:21 +00001583 }
1584
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001585 // FIXME: The following handlers should use a callback mechanism, we don't
1586 // know what the client would like to do.
Daniel Dunbarf0eddb82009-03-18 02:55:38 +00001587 if (Arg *A = C.getArgs().getLastArg(options::OPT_print_file_name_EQ)) {
Richard Smithbd55daf2012-11-01 04:30:05 +00001588 llvm::outs() << GetFilePath(A->getValue(), TC) << "\n";
Daniel Dunbar5e0f6af2009-03-13 00:51:18 +00001589 return false;
1590 }
1591
Daniel Dunbarf0eddb82009-03-18 02:55:38 +00001592 if (Arg *A = C.getArgs().getLastArg(options::OPT_print_prog_name_EQ)) {
Richard Smithbd55daf2012-11-01 04:30:05 +00001593 llvm::outs() << GetProgramPath(A->getValue(), TC) << "\n";
Daniel Dunbar5e0f6af2009-03-13 00:51:18 +00001594 return false;
1595 }
1596
Yuka Takahashic8068db2017-05-23 18:39:08 +00001597 if (Arg *A = C.getArgs().getLastArg(options::OPT_autocomplete)) {
Yuka Takahashiba5d4af2017-06-20 16:31:31 +00001598 StringRef PassedFlags = A->getValue();
Yuka Takahashi41789e42018-03-05 08:54:20 +00001599 HandleAutocompletions(PassedFlags);
Yuka Takahashic8068db2017-05-23 18:39:08 +00001600 return false;
1601 }
1602
Daniel Dunbarf0eddb82009-03-18 02:55:38 +00001603 if (C.getArgs().hasArg(options::OPT_print_libgcc_file_name)) {
Michal Gorny7cfe4802016-10-10 12:23:40 +00001604 ToolChain::RuntimeLibType RLT = TC.GetRuntimeLibType(C.getArgs());
Leo Li23bb21c2017-08-24 01:51:51 +00001605 const llvm::Triple Triple(TC.ComputeEffectiveClangTriple(C.getArgs()));
1606 RegisterEffectiveTriple TripleRAII(TC, Triple);
Michal Gorny7cfe4802016-10-10 12:23:40 +00001607 switch (RLT) {
1608 case ToolChain::RLT_CompilerRT:
1609 llvm::outs() << TC.getCompilerRT(C.getArgs(), "builtins") << "\n";
1610 break;
1611 case ToolChain::RLT_Libgcc:
1612 llvm::outs() << GetFilePath("libgcc.a", TC) << "\n";
1613 break;
1614 }
Daniel Dunbar5e0f6af2009-03-13 00:51:18 +00001615 return false;
1616 }
1617
Daniel Dunbar1b3ec3a2009-06-16 23:25:22 +00001618 if (C.getArgs().hasArg(options::OPT_print_multi_lib)) {
Douglas Katzmana34b7bf2015-06-30 19:32:57 +00001619 for (const Multilib &Multilib : TC.getMultilibs())
1620 llvm::outs() << Multilib << "\n";
Daniel Dunbar1b3ec3a2009-06-16 23:25:22 +00001621 return false;
1622 }
1623
Jonathan Roelofs2cea1be2014-02-12 03:21:20 +00001624 if (C.getArgs().hasArg(options::OPT_print_multi_directory)) {
Douglas Katzmana34b7bf2015-06-30 19:32:57 +00001625 for (const Multilib &Multilib : TC.getMultilibs()) {
Douglas Katzman6bbffc42015-06-25 18:51:37 +00001626 if (Multilib.gccSuffix().empty())
Jonathan Roelofs2cea1be2014-02-12 03:21:20 +00001627 llvm::outs() << ".\n";
1628 else {
Douglas Katzman6bbffc42015-06-25 18:51:37 +00001629 StringRef Suffix(Multilib.gccSuffix());
Jonathan Roelofs2cea1be2014-02-12 03:21:20 +00001630 assert(Suffix.front() == '/');
1631 llvm::outs() << Suffix.substr(1) << "\n";
1632 }
Jonathan Roelofs3fa96d82014-02-12 01:36:51 +00001633 }
Jonathan Roelofs0e7ec602014-02-12 01:29:25 +00001634 return false;
1635 }
Daniel Dunbar5e0f6af2009-03-13 00:51:18 +00001636 return true;
1637}
1638
Douglas Katzmanfd528672015-06-11 15:05:22 +00001639// Display an action graph human-readably. Action A is the "sink" node
1640// and latest-occuring action. Traversal is in pre-order, visiting the
1641// inputs to each action before printing the action itself.
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001642static unsigned PrintActions1(const Compilation &C, Action *A,
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001643 std::map<Action *, unsigned> &Ids) {
Douglas Katzmanfd528672015-06-11 15:05:22 +00001644 if (Ids.count(A)) // A was already visited.
Daniel Dunbaraaf1ea62009-03-13 12:19:02 +00001645 return Ids[A];
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001646
Daniel Dunbaraaf1ea62009-03-13 12:19:02 +00001647 std::string str;
1648 llvm::raw_string_ostream os(str);
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001649
Daniel Dunbaraaf1ea62009-03-13 12:19:02 +00001650 os << Action::getClassName(A->getKind()) << ", ";
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001651 if (InputAction *IA = dyn_cast<InputAction>(A)) {
Richard Smithbd55daf2012-11-01 04:30:05 +00001652 os << "\"" << IA->getInputArg().getValue() << "\"";
Daniel Dunbaraaf1ea62009-03-13 12:19:02 +00001653 } else if (BindArchAction *BIA = dyn_cast<BindArchAction>(A)) {
Douglas Katzmanb7e8ef02015-06-25 19:37:41 +00001654 os << '"' << BIA->getArchName() << '"' << ", {"
Nico Weber5a459f82016-02-23 19:30:43 +00001655 << PrintActions1(C, *BIA->input_begin(), Ids) << "}";
Samuel Antaod06239d2016-07-15 23:13:27 +00001656 } else if (OffloadAction *OA = dyn_cast<OffloadAction>(A)) {
1657 bool IsFirst = true;
1658 OA->doOnEachDependence(
1659 [&](Action *A, const ToolChain *TC, const char *BoundArch) {
1660 // E.g. for two CUDA device dependences whose bound arch is sm_20 and
1661 // sm_35 this will generate:
1662 // "cuda-device" (nvptx64-nvidia-cuda:sm_20) {#ID}, "cuda-device"
1663 // (nvptx64-nvidia-cuda:sm_35) {#ID}
1664 if (!IsFirst)
1665 os << ", ";
1666 os << '"';
1667 if (TC)
1668 os << A->getOffloadingKindPrefix();
1669 else
1670 os << "host";
1671 os << " (";
1672 os << TC->getTriple().normalize();
1673
1674 if (BoundArch)
1675 os << ":" << BoundArch;
1676 os << ")";
1677 os << '"';
1678 os << " {" << PrintActions1(C, A, Ids) << "}";
1679 IsFirst = false;
1680 });
Daniel Dunbaraaf1ea62009-03-13 12:19:02 +00001681 } else {
Samuel Antaod06239d2016-07-15 23:13:27 +00001682 const ActionList *AL = &A->getInputs();
Artem Belevich0ff05cd2015-07-13 23:27:56 +00001683
Artem Belevich23256752015-09-22 17:23:09 +00001684 if (AL->size()) {
1685 const char *Prefix = "{";
1686 for (Action *PreRequisite : *AL) {
1687 os << Prefix << PrintActions1(C, PreRequisite, Ids);
1688 Prefix = ", ";
1689 }
1690 os << "}";
1691 } else
1692 os << "{}";
Daniel Dunbaraaf1ea62009-03-13 12:19:02 +00001693 }
1694
Samuel Antaod06239d2016-07-15 23:13:27 +00001695 // Append offload info for all options other than the offloading action
1696 // itself (e.g. (cuda-device, sm_20) or (cuda-host)).
1697 std::string offload_str;
1698 llvm::raw_string_ostream offload_os(offload_str);
1699 if (!isa<OffloadAction>(A)) {
1700 auto S = A->getOffloadingKindPrefix();
1701 if (!S.empty()) {
1702 offload_os << ", (" << S;
1703 if (A->getOffloadingArch())
1704 offload_os << ", " << A->getOffloadingArch();
1705 offload_os << ")";
1706 }
1707 }
1708
Daniel Dunbaraaf1ea62009-03-13 12:19:02 +00001709 unsigned Id = Ids.size();
1710 Ids[A] = Id;
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001711 llvm::errs() << Id << ": " << os.str() << ", "
Samuel Antaod06239d2016-07-15 23:13:27 +00001712 << types::getTypeName(A->getType()) << offload_os.str() << "\n";
Daniel Dunbaraaf1ea62009-03-13 12:19:02 +00001713
1714 return Id;
1715}
1716
Douglas Katzmanfd528672015-06-11 15:05:22 +00001717// Print the action graphs in a compilation C.
1718// For example "clang -c file1.c file2.c" is composed of two subgraphs.
Daniel Dunbareb843be2009-03-18 03:13:20 +00001719void Driver::PrintActions(const Compilation &C) const {
Douglas Katzmanb7e8ef02015-06-25 19:37:41 +00001720 std::map<Action *, unsigned> Ids;
1721 for (Action *A : C.getActions())
1722 PrintActions1(C, A, Ids);
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00001723}
1724
Joerg Sonnenberger5fe4a7d2011-05-06 14:05:11 +00001725/// \brief Check whether the given input tree contains any compilation or
1726/// assembly actions.
1727static bool ContainsCompileOrAssembleAction(const Action *A) {
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001728 if (isa<CompileJobAction>(A) || isa<BackendJobAction>(A) ||
Bob Wilson23a55f12014-12-21 07:00:00 +00001729 isa<AssembleJobAction>(A))
Daniel Dunbar00d3d8e2010-06-29 16:38:33 +00001730 return true;
1731
Nico Weber5a459f82016-02-23 19:30:43 +00001732 for (const Action *Input : A->inputs())
Nico Weberfb80f962015-09-19 21:36:51 +00001733 if (ContainsCompileOrAssembleAction(Input))
Daniel Dunbar00d3d8e2010-06-29 16:38:33 +00001734 return true;
1735
1736 return false;
1737}
1738
Artem Belevich5e2a3ec2015-11-17 22:28:40 +00001739void Driver::BuildUniversalActions(Compilation &C, const ToolChain &TC,
1740 const InputList &BAInputs) const {
1741 DerivedArgList &Args = C.getArgs();
1742 ActionList &Actions = C.getActions();
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001743 llvm::PrettyStackTraceString CrashInfo("Building universal build actions");
1744 // Collect the list of architectures. Duplicates are allowed, but should only
1745 // be handled once (in the order seen).
Daniel Dunbare5dc4822009-03-13 20:33:35 +00001746 llvm::StringSet<> ArchNames;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001747 SmallVector<const char *, 4> Archs;
Saleem Abdulrasool688b6bc2014-12-29 19:01:36 +00001748 for (Arg *A : Args) {
Daniel Dunbar0bfb21e2009-11-19 03:26:40 +00001749 if (A->getOption().matches(options::OPT_arch)) {
Daniel Dunbar9c3f7c42009-09-08 23:37:30 +00001750 // Validate the option here; we don't save the type here because its
1751 // particular spelling may participate in other driver choices.
1752 llvm::Triple::ArchType Arch =
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001753 tools::darwin::getArchTypeForMachOArchName(A->getValue());
Daniel Dunbar9c3f7c42009-09-08 23:37:30 +00001754 if (Arch == llvm::Triple::UnknownArch) {
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001755 Diag(clang::diag::err_drv_invalid_arch_name) << A->getAsString(Args);
Daniel Dunbar9c3f7c42009-09-08 23:37:30 +00001756 continue;
1757 }
1758
Daniel Dunbar2da02722009-03-19 07:55:12 +00001759 A->claim();
David Blaikie61b86d42014-11-19 02:56:13 +00001760 if (ArchNames.insert(A->getValue()).second)
Richard Smithbd55daf2012-11-01 04:30:05 +00001761 Archs.push_back(A->getValue());
Daniel Dunbarf479c122009-03-12 18:40:18 +00001762 }
1763 }
1764
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001765 // When there is no explicit arch for this platform, make sure we still bind
1766 // the architecture (to the default) so that -Xarch_ is handled correctly.
Daniel Dunbareb843be2009-03-18 03:13:20 +00001767 if (!Archs.size())
Daniel Dunbarc3bd9f52012-11-08 03:38:26 +00001768 Archs.push_back(Args.MakeArgString(TC.getDefaultUniversalArchName()));
Daniel Dunbarf479c122009-03-12 18:40:18 +00001769
Daniel Dunbarf479c122009-03-12 18:40:18 +00001770 ActionList SingleActions;
Justin Lebar0f3474c2016-02-11 02:00:50 +00001771 BuildActions(C, Args, BAInputs, SingleActions);
Daniel Dunbarf479c122009-03-12 18:40:18 +00001772
Daniel Dunbar6beaf512010-06-04 18:28:41 +00001773 // Add in arch bindings for every top level action, as well as lipo and
1774 // dsymutil steps if needed.
Nico Weberfb80f962015-09-19 21:36:51 +00001775 for (Action* Act : SingleActions) {
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001776 // Make sure we can lipo this kind of output. If not (and it is an actual
1777 // output) then we disallow, since we can't create an output file with the
1778 // right name without overwriting it. We could remove this oddity by just
1779 // changing the output names to include the arch, which would also fix
Daniel Dunbarf479c122009-03-12 18:40:18 +00001780 // -save-temps. Compatibility wins for now.
1781
Daniel Dunbare2ca3bd2009-03-13 17:46:02 +00001782 if (Archs.size() > 1 && !types::canLipoType(Act->getType()))
Daniel Dunbarf479c122009-03-12 18:40:18 +00001783 Diag(clang::diag::err_drv_invalid_output_with_multiple_archs)
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001784 << types::getTypeName(Act->getType());
Daniel Dunbarf479c122009-03-12 18:40:18 +00001785
1786 ActionList Inputs;
Justin Lebar41094612016-01-11 23:07:27 +00001787 for (unsigned i = 0, e = Archs.size(); i != e; ++i)
1788 Inputs.push_back(C.MakeAction<BindArchAction>(Act, Archs[i]));
Daniel Dunbarf479c122009-03-12 18:40:18 +00001789
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001790 // Lipo if necessary, we do it this way because we need to set the arch flag
1791 // so that -Xarch_ gets overwritten.
Daniel Dunbarf479c122009-03-12 18:40:18 +00001792 if (Inputs.size() == 1 || Act->getType() == types::TY_Nothing)
1793 Actions.append(Inputs.begin(), Inputs.end());
1794 else
Justin Lebar41094612016-01-11 23:07:27 +00001795 Actions.push_back(C.MakeAction<LipoJobAction>(Inputs, Act->getType()));
Daniel Dunbar6beaf512010-06-04 18:28:41 +00001796
Eric Christopher65c05fa2012-02-06 19:43:51 +00001797 // Handle debug info queries.
1798 Arg *A = Args.getLastArg(options::OPT_g_Group);
David Blaikie6f9f4eb2012-04-15 21:22:10 +00001799 if (A && !A->getOption().matches(options::OPT_g0) &&
1800 !A->getOption().matches(options::OPT_gstabs) &&
1801 ContainsCompileOrAssembleAction(Actions.back())) {
Chad Rosier62135492012-07-09 17:31:28 +00001802
David Blaikie6f9f4eb2012-04-15 21:22:10 +00001803 // Add a 'dsymutil' step if necessary, when debug info is enabled and we
1804 // have a compile input. We need to run 'dsymutil' ourselves in such cases
Eric Christopher776c26f2013-01-28 17:39:03 +00001805 // because the debug info will refer to a temporary object file which
David Blaikie6f9f4eb2012-04-15 21:22:10 +00001806 // will be removed at the end of the compilation process.
1807 if (Act->getType() == types::TY_Image) {
1808 ActionList Inputs;
1809 Inputs.push_back(Actions.back());
1810 Actions.pop_back();
Justin Lebar41094612016-01-11 23:07:27 +00001811 Actions.push_back(
1812 C.MakeAction<DsymutilJobAction>(Inputs, types::TY_dSYM));
Daniel Dunbar6beaf512010-06-04 18:28:41 +00001813 }
David Blaikie6f9f4eb2012-04-15 21:22:10 +00001814
Ben Langmuir9b9a8d32014-02-06 18:53:25 +00001815 // Verify the debug info output.
Alp Tokere9d2bfc2014-01-17 02:06:23 +00001816 if (Args.hasArg(options::OPT_verify_debug_info)) {
Justin Lebar41094612016-01-11 23:07:27 +00001817 Action* LastAction = Actions.back();
David Blaikie6f9f4eb2012-04-15 21:22:10 +00001818 Actions.pop_back();
Justin Lebar41094612016-01-11 23:07:27 +00001819 Actions.push_back(C.MakeAction<VerifyDebugInfoJobAction>(
1820 LastAction, types::TY_Nothing));
David Blaikie6f9f4eb2012-04-15 21:22:10 +00001821 }
1822 }
Daniel Dunbarf479c122009-03-12 18:40:18 +00001823 }
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00001824}
1825
Hans Wennborg6ee64d52013-08-06 00:20:31 +00001826/// \brief Check that the file referenced by Value exists. If it doesn't,
1827/// issue a diagnostic and return false.
Alp Toker8c8a8752013-12-03 06:53:35 +00001828static bool DiagnoseInputExistence(const Driver &D, const DerivedArgList &Args,
Hans Wennborg12f4f8b2016-04-15 01:12:32 +00001829 StringRef Value, types::ID Ty) {
Hans Wennborg6ee64d52013-08-06 00:20:31 +00001830 if (!D.getCheckInputsExist())
1831 return true;
1832
1833 // stdin always exists.
1834 if (Value == "-")
1835 return true;
1836
1837 SmallString<64> Path(Value);
1838 if (Arg *WorkDir = Args.getLastArg(options::OPT_working_directory)) {
Yaron Keren92e1b622015-03-18 10:17:07 +00001839 if (!llvm::sys::path::is_absolute(Path)) {
Hans Wennborg6ee64d52013-08-06 00:20:31 +00001840 SmallString<64> Directory(WorkDir->getValue());
1841 llvm::sys::path::append(Directory, Value);
1842 Path.assign(Directory);
1843 }
1844 }
1845
1846 if (llvm::sys::fs::exists(Twine(Path)))
1847 return true;
1848
Hans Wennborg12f4f8b2016-04-15 01:12:32 +00001849 if (D.IsCLMode()) {
1850 if (!llvm::sys::path::is_absolute(Twine(Path)) &&
1851 llvm::sys::Process::FindInEnvPath("LIB", Value))
1852 return true;
1853
1854 if (Args.hasArg(options::OPT__SLASH_link) && Ty == types::TY_Object) {
1855 // Arguments to the /link flag might cause the linker to search for object
1856 // and library files in paths we don't know about. Don't error in such
1857 // cases.
1858 return true;
1859 }
1860 }
Hans Wennborg23d26a32014-06-18 17:21:50 +00001861
Yaron Keren92e1b622015-03-18 10:17:07 +00001862 D.Diag(clang::diag::err_drv_no_such_file) << Path;
Hans Wennborg6ee64d52013-08-06 00:20:31 +00001863 return false;
1864}
1865
Chad Rosierecdede82011-08-12 22:08:57 +00001866// Construct a the list of inputs and their types.
Hans Wennborg55362852014-05-02 22:55:30 +00001867void Driver::BuildInputs(const ToolChain &TC, DerivedArgList &Args,
Chad Rosierecdede82011-08-12 22:08:57 +00001868 InputList &Inputs) const {
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001869 // Track the current user specified (-x) input. We also explicitly track the
1870 // argument used to set the type; we only want to claim the type when we
1871 // actually use it, so we warn about unused -x arguments.
Daniel Dunbarc5a5ac52009-03-13 17:57:10 +00001872 types::ID InputType = types::TY_Nothing;
Craig Topper92fc2df2014-05-17 16:56:41 +00001873 Arg *InputTypeArg = nullptr;
Daniel Dunbarc5a5ac52009-03-13 17:57:10 +00001874
Hans Wennborg0d0b19c2013-08-12 18:34:17 +00001875 // The last /TC or /TP option sets the input type to C or C++ globally.
Ehsan Akhgaric249abb2014-09-12 21:44:24 +00001876 if (Arg *TCTP = Args.getLastArgNoClaim(options::OPT__SLASH_TC,
1877 options::OPT__SLASH_TP)) {
Hans Wennborg6ee64d52013-08-06 00:20:31 +00001878 InputTypeArg = TCTP;
Hans Wennborg0d0b19c2013-08-12 18:34:17 +00001879 InputType = TCTP->getOption().matches(options::OPT__SLASH_TC)
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001880 ? types::TY_C
1881 : types::TY_CXX;
Hans Wennborg6ee64d52013-08-06 00:20:31 +00001882
Richard Smith0aef3052017-02-18 01:14:43 +00001883 Arg *Previous = nullptr;
Hans Wennborg0d0b19c2013-08-12 18:34:17 +00001884 bool ShowNote = false;
Richard Smith0aef3052017-02-18 01:14:43 +00001885 for (Arg *A : Args.filtered(options::OPT__SLASH_TC, options::OPT__SLASH_TP)) {
1886 if (Previous) {
1887 Diag(clang::diag::warn_drv_overriding_flag_option)
1888 << Previous->getSpelling() << A->getSpelling();
1889 ShowNote = true;
1890 }
1891 Previous = A;
Hans Wennborg6ee64d52013-08-06 00:20:31 +00001892 }
Hans Wennborg0d0b19c2013-08-12 18:34:17 +00001893 if (ShowNote)
1894 Diag(clang::diag::note_drv_t_option_is_global);
Hans Wennborg6ee64d52013-08-06 00:20:31 +00001895
1896 // No driver mode exposes -x and /TC or /TP; we don't support mixing them.
1897 assert(!Args.hasArg(options::OPT_x) && "-x and /TC or /TP is not allowed");
1898 }
1899
Saleem Abdulrasool688b6bc2014-12-29 19:01:36 +00001900 for (Arg *A : Args) {
Michael J. Spencerad3ccc32012-08-20 21:41:17 +00001901 if (A->getOption().getKind() == Option::InputClass) {
Richard Smithbd55daf2012-11-01 04:30:05 +00001902 const char *Value = A->getValue();
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00001903 types::ID Ty = types::TY_INVALID;
1904
1905 // Infer the input type if necessary.
Daniel Dunbarc5a5ac52009-03-13 17:57:10 +00001906 if (InputType == types::TY_Nothing) {
1907 // If there was an explicit arg for this, claim it.
1908 if (InputTypeArg)
1909 InputTypeArg->claim();
1910
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00001911 // stdin must be handled specially.
1912 if (memcmp(Value, "-", 2) == 0) {
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001913 // If running with -E, treat as a C input (this changes the builtin
1914 // macros, for example). This may be overridden by -ObjC below.
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00001915 //
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001916 // Otherwise emit an error but still use a valid type to avoid
1917 // spurious errors (e.g., no inputs).
Hans Wennborg70850d82013-07-18 20:29:38 +00001918 if (!Args.hasArgNoClaim(options::OPT_E) && !CCCIsCPP())
Hans Wennborgcfdd8b52014-01-29 01:04:40 +00001919 Diag(IsCLMode() ? clang::diag::err_drv_unknown_stdin_type_clang_cl
1920 : clang::diag::err_drv_unknown_stdin_type);
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00001921 Ty = types::TY_C;
1922 } else {
Joerg Sonnenbergerbdbdf702011-03-16 22:45:02 +00001923 // Otherwise lookup by extension.
1924 // Fallback is C if invoked as C preprocessor or Object otherwise.
1925 // We use a host hook here because Darwin at least has its own
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001926 // idea of what .s is.
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00001927 if (const char *Ext = strrchr(Value, '.'))
Daniel Dunbarcc7df6c2010-08-02 05:43:56 +00001928 Ty = TC.LookupTypeForExtension(Ext + 1);
Daniel Dunbarea9f0322009-03-20 23:39:23 +00001929
Joerg Sonnenbergerbdbdf702011-03-16 22:45:02 +00001930 if (Ty == types::TY_INVALID) {
Hans Wennborg70850d82013-07-18 20:29:38 +00001931 if (CCCIsCPP())
Joerg Sonnenbergerbdbdf702011-03-16 22:45:02 +00001932 Ty = types::TY_C;
1933 else
1934 Ty = types::TY_Object;
1935 }
Daniel Dunbar0ac94452010-02-17 20:32:58 +00001936
1937 // If the driver is invoked as C++ compiler (like clang++ or c++) it
1938 // should autodetect some input files as C++ for g++ compatibility.
Hans Wennborg70850d82013-07-18 20:29:38 +00001939 if (CCCIsCXX()) {
Daniel Dunbar0ac94452010-02-17 20:32:58 +00001940 types::ID OldTy = Ty;
1941 Ty = types::lookupCXXTypeForCType(Ty);
1942
1943 if (Ty != OldTy)
1944 Diag(clang::diag::warn_drv_treating_input_as_cxx)
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001945 << getTypeName(OldTy) << getTypeName(Ty);
Daniel Dunbar0ac94452010-02-17 20:32:58 +00001946 }
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00001947 }
1948
Daniel Dunbar82b22102009-05-18 21:47:54 +00001949 // -ObjC and -ObjC++ override the default language, but only for "source
1950 // files". We just treat everything that isn't a linker input as a
1951 // source file.
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001952 //
Daniel Dunbar82b22102009-05-18 21:47:54 +00001953 // FIXME: Clean this up if we move the phase sequence into the type.
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00001954 if (Ty != types::TY_Object) {
1955 if (Args.hasArg(options::OPT_ObjC))
1956 Ty = types::TY_ObjC;
1957 else if (Args.hasArg(options::OPT_ObjCXX))
1958 Ty = types::TY_ObjCXX;
1959 }
1960 } else {
1961 assert(InputTypeArg && "InputType set w/o InputTypeArg");
Ehsan Akhgari7e954ea2014-09-12 18:15:10 +00001962 if (!InputTypeArg->getOption().matches(options::OPT_x)) {
1963 // If emulating cl.exe, make sure that /TC and /TP don't affect input
1964 // object files.
1965 const char *Ext = strrchr(Value, '.');
1966 if (Ext && TC.LookupTypeForExtension(Ext + 1) == types::TY_Object)
1967 Ty = types::TY_Object;
1968 }
1969 if (Ty == types::TY_INVALID) {
1970 Ty = InputType;
1971 InputTypeArg->claim();
1972 }
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00001973 }
1974
Hans Wennborg12f4f8b2016-04-15 01:12:32 +00001975 if (DiagnoseInputExistence(*this, Args, Value, Ty))
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00001976 Inputs.push_back(std::make_pair(Ty, A));
1977
Hans Wennborg6ee64d52013-08-06 00:20:31 +00001978 } else if (A->getOption().matches(options::OPT__SLASH_Tc)) {
1979 StringRef Value = A->getValue();
Hans Wennborg12f4f8b2016-04-15 01:12:32 +00001980 if (DiagnoseInputExistence(*this, Args, Value, types::TY_C)) {
David Blaikie0aaa7622017-01-13 17:34:15 +00001981 Arg *InputArg = MakeInputArg(Args, *Opts, A->getValue());
Hans Wennborg6ee64d52013-08-06 00:20:31 +00001982 Inputs.push_back(std::make_pair(types::TY_C, InputArg));
1983 }
1984 A->claim();
1985 } else if (A->getOption().matches(options::OPT__SLASH_Tp)) {
1986 StringRef Value = A->getValue();
Hans Wennborg12f4f8b2016-04-15 01:12:32 +00001987 if (DiagnoseInputExistence(*this, Args, Value, types::TY_CXX)) {
David Blaikie0aaa7622017-01-13 17:34:15 +00001988 Arg *InputArg = MakeInputArg(Args, *Opts, A->getValue());
Hans Wennborg6ee64d52013-08-06 00:20:31 +00001989 Inputs.push_back(std::make_pair(types::TY_CXX, InputArg));
1990 }
1991 A->claim();
Michael J. Spencer66e2b202012-10-19 22:37:06 +00001992 } else if (A->getOption().hasFlag(options::LinkerInput)) {
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001993 // Just treat as object type, we could make a special type for this if
1994 // necessary.
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00001995 Inputs.push_back(std::make_pair(types::TY_Object, A));
1996
Daniel Dunbar0bfb21e2009-11-19 03:26:40 +00001997 } else if (A->getOption().matches(options::OPT_x)) {
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001998 InputTypeArg = A;
Richard Smithbd55daf2012-11-01 04:30:05 +00001999 InputType = types::lookupTypeForTypeSpecifier(A->getValue());
Chad Rosier706c2352012-04-07 00:01:31 +00002000 A->claim();
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00002001
2002 // Follow gcc behavior and treat as linker input for invalid -x
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00002003 // options. Its not clear why we shouldn't just revert to unknown; but
Michael J. Spencer1a4fe8c2010-12-17 21:22:33 +00002004 // this isn't very important, we might as well be bug compatible.
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00002005 if (!InputType) {
Richard Smithbd55daf2012-11-01 04:30:05 +00002006 Diag(clang::diag::err_drv_unknown_language) << A->getValue();
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00002007 InputType = types::TY_Object;
2008 }
Hans Wennborg091f1b62017-01-27 17:09:41 +00002009 } else if (A->getOption().getID() == options::OPT__SLASH_U) {
2010 assert(A->getNumValues() == 1 && "The /U option has one value.");
2011 StringRef Val = A->getValue(0);
2012 if (Val.find_first_of("/\\") != StringRef::npos) {
2013 // Warn about e.g. "/Users/me/myfile.c".
2014 Diag(diag::warn_slash_u_filename) << Val;
2015 Diag(diag::note_use_dashdash);
2016 }
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00002017 }
2018 }
Hans Wennborg70850d82013-07-18 20:29:38 +00002019 if (CCCIsCPP() && Inputs.empty()) {
Joerg Sonnenbergerb86f5f42011-03-06 23:31:01 +00002020 // If called as standalone preprocessor, stdin is processed
2021 // if no other input is present.
David Blaikie0aaa7622017-01-13 17:34:15 +00002022 Arg *A = MakeInputArg(Args, *Opts, "-");
Joerg Sonnenbergerb86f5f42011-03-06 23:31:01 +00002023 Inputs.push_back(std::make_pair(types::TY_C, A));
2024 }
Chad Rosierecdede82011-08-12 22:08:57 +00002025}
2026
Samuel Antao64e965e2016-09-30 15:34:19 +00002027namespace {
2028/// Provides a convenient interface for different programming models to generate
2029/// the required device actions.
2030class OffloadingActionBuilder final {
2031 /// Flag used to trace errors in the builder.
2032 bool IsValid = false;
2033
2034 /// The compilation that is using this builder.
2035 Compilation &C;
2036
Samuel Antao64e965e2016-09-30 15:34:19 +00002037 /// Map between an input argument and the offload kinds used to process it.
2038 std::map<const Arg *, unsigned> InputArgToOffloadKindMap;
2039
2040 /// Builder interface. It doesn't build anything or keep any state.
2041 class DeviceActionBuilder {
2042 public:
2043 typedef llvm::SmallVector<phases::ID, phases::MaxNumberOfPhases> PhasesTy;
2044
2045 enum ActionBuilderReturnCode {
2046 // The builder acted successfully on the current action.
2047 ABRT_Success,
2048 // The builder didn't have to act on the current action.
2049 ABRT_Inactive,
2050 // The builder was successful and requested the host action to not be
2051 // generated.
2052 ABRT_Ignore_Host,
2053 };
2054
2055 protected:
2056 /// Compilation associated with this builder.
2057 Compilation &C;
2058
2059 /// Tool chains associated with this builder. The same programming
2060 /// model may have associated one or more tool chains.
2061 SmallVector<const ToolChain *, 2> ToolChains;
2062
2063 /// The derived arguments associated with this builder.
2064 DerivedArgList &Args;
2065
2066 /// The inputs associated with this builder.
2067 const Driver::InputList &Inputs;
2068
2069 /// The associated offload kind.
2070 Action::OffloadKind AssociatedOffloadKind = Action::OFK_None;
2071
2072 public:
2073 DeviceActionBuilder(Compilation &C, DerivedArgList &Args,
2074 const Driver::InputList &Inputs,
2075 Action::OffloadKind AssociatedOffloadKind)
2076 : C(C), Args(Args), Inputs(Inputs),
2077 AssociatedOffloadKind(AssociatedOffloadKind) {}
2078 virtual ~DeviceActionBuilder() {}
2079
2080 /// Fill up the array \a DA with all the device dependences that should be
2081 /// added to the provided host action \a HostAction. By default it is
2082 /// inactive.
2083 virtual ActionBuilderReturnCode
Samuel Antao28c4f182016-10-27 17:08:03 +00002084 getDeviceDependences(OffloadAction::DeviceDependences &DA,
2085 phases::ID CurPhase, phases::ID FinalPhase,
2086 PhasesTy &Phases) {
Samuel Antao64e965e2016-09-30 15:34:19 +00002087 return ABRT_Inactive;
2088 }
2089
2090 /// Update the state to include the provided host action \a HostAction as a
2091 /// dependency of the current device action. By default it is inactive.
2092 virtual ActionBuilderReturnCode addDeviceDepences(Action *HostAction) {
2093 return ABRT_Inactive;
2094 }
2095
2096 /// Append top level actions generated by the builder. Return true if errors
2097 /// were found.
2098 virtual void appendTopLevelActions(ActionList &AL) {}
2099
2100 /// Append linker actions generated by the builder. Return true if errors
2101 /// were found.
2102 virtual void appendLinkDependences(OffloadAction::DeviceDependences &DA) {}
2103
2104 /// Initialize the builder. Return true if any initialization errors are
2105 /// found.
2106 virtual bool initialize() { return false; }
2107
Samuel Antao69d6f312016-10-27 17:50:43 +00002108 /// Return true if the builder can use bundling/unbundling.
2109 virtual bool canUseBundlerUnbundler() const { return false; }
2110
Samuel Antao64e965e2016-09-30 15:34:19 +00002111 /// Return true if this builder is valid. We have a valid builder if we have
2112 /// associated device tool chains.
2113 bool isValid() { return !ToolChains.empty(); }
2114
2115 /// Return the associated offload kind.
2116 Action::OffloadKind getAssociatedOffloadKind() {
2117 return AssociatedOffloadKind;
2118 }
2119 };
2120
2121 /// \brief CUDA action builder. It injects device code in the host backend
2122 /// action.
2123 class CudaActionBuilder final : public DeviceActionBuilder {
2124 /// Flags to signal if the user requested host-only or device-only
2125 /// compilation.
2126 bool CompileHostOnly = false;
2127 bool CompileDeviceOnly = false;
2128
2129 /// List of GPU architectures to use in this compilation.
2130 SmallVector<CudaArch, 4> GpuArchList;
2131
2132 /// The CUDA actions for the current input.
2133 ActionList CudaDeviceActions;
2134
2135 /// The CUDA fat binary if it was generated for the current input.
2136 Action *CudaFatBinary = nullptr;
2137
2138 /// Flag that is set to true if this builder acted on the current input.
2139 bool IsActive = false;
2140
2141 public:
2142 CudaActionBuilder(Compilation &C, DerivedArgList &Args,
2143 const Driver::InputList &Inputs)
2144 : DeviceActionBuilder(C, Args, Inputs, Action::OFK_Cuda) {}
2145
2146 ActionBuilderReturnCode
Samuel Antao28c4f182016-10-27 17:08:03 +00002147 getDeviceDependences(OffloadAction::DeviceDependences &DA,
2148 phases::ID CurPhase, phases::ID FinalPhase,
2149 PhasesTy &Phases) override {
Samuel Antao64e965e2016-09-30 15:34:19 +00002150 if (!IsActive)
2151 return ABRT_Inactive;
2152
2153 // If we don't have more CUDA actions, we don't have any dependences to
2154 // create for the host.
2155 if (CudaDeviceActions.empty())
2156 return ABRT_Success;
2157
2158 assert(CudaDeviceActions.size() == GpuArchList.size() &&
2159 "Expecting one action per GPU architecture.");
2160 assert(!CompileHostOnly &&
2161 "Not expecting CUDA actions in host-only compilation.");
2162
2163 // If we are generating code for the device or we are in a backend phase,
2164 // we attempt to generate the fat binary. We compile each arch to ptx and
2165 // assemble to cubin, then feed the cubin *and* the ptx into a device
2166 // "link" action, which uses fatbinary to combine these cubins into one
2167 // fatbin. The fatbin is then an input to the host action if not in
2168 // device-only mode.
2169 if (CompileDeviceOnly || CurPhase == phases::Backend) {
2170 ActionList DeviceActions;
2171 for (unsigned I = 0, E = GpuArchList.size(); I != E; ++I) {
2172 // Produce the device action from the current phase up to the assemble
2173 // phase.
2174 for (auto Ph : Phases) {
2175 // Skip the phases that were already dealt with.
2176 if (Ph < CurPhase)
2177 continue;
2178 // We have to be consistent with the host final phase.
2179 if (Ph > FinalPhase)
2180 break;
2181
2182 CudaDeviceActions[I] = C.getDriver().ConstructPhaseAction(
Artem Belevichecb178b2018-03-21 22:22:59 +00002183 C, Args, Ph, CudaDeviceActions[I], Action::OFK_Cuda);
Samuel Antao64e965e2016-09-30 15:34:19 +00002184
2185 if (Ph == phases::Assemble)
2186 break;
2187 }
2188
2189 // If we didn't reach the assemble phase, we can't generate the fat
2190 // binary. We don't need to generate the fat binary if we are not in
2191 // device-only mode.
2192 if (!isa<AssembleJobAction>(CudaDeviceActions[I]) ||
2193 CompileDeviceOnly)
2194 continue;
2195
2196 Action *AssembleAction = CudaDeviceActions[I];
2197 assert(AssembleAction->getType() == types::TY_Object);
2198 assert(AssembleAction->getInputs().size() == 1);
2199
2200 Action *BackendAction = AssembleAction->getInputs()[0];
2201 assert(BackendAction->getType() == types::TY_PP_Asm);
2202
2203 for (auto &A : {AssembleAction, BackendAction}) {
2204 OffloadAction::DeviceDependences DDep;
2205 DDep.add(*A, *ToolChains.front(), CudaArchToString(GpuArchList[I]),
2206 Action::OFK_Cuda);
2207 DeviceActions.push_back(
2208 C.MakeAction<OffloadAction>(DDep, A->getType()));
2209 }
2210 }
2211
2212 // We generate the fat binary if we have device input actions.
2213 if (!DeviceActions.empty()) {
2214 CudaFatBinary =
2215 C.MakeAction<LinkJobAction>(DeviceActions, types::TY_CUDA_FATBIN);
2216
2217 if (!CompileDeviceOnly) {
2218 DA.add(*CudaFatBinary, *ToolChains.front(), /*BoundArch=*/nullptr,
2219 Action::OFK_Cuda);
2220 // Clear the fat binary, it is already a dependence to an host
2221 // action.
2222 CudaFatBinary = nullptr;
2223 }
2224
2225 // Remove the CUDA actions as they are already connected to an host
2226 // action or fat binary.
2227 CudaDeviceActions.clear();
2228 }
2229
2230 // We avoid creating host action in device-only mode.
2231 return CompileDeviceOnly ? ABRT_Ignore_Host : ABRT_Success;
Samuel Antao5b1a89a2016-10-27 00:53:34 +00002232 } else if (CurPhase > phases::Backend) {
2233 // If we are past the backend phase and still have a device action, we
2234 // don't have to do anything as this action is already a device
2235 // top-level action.
2236 return ABRT_Success;
Samuel Antao64e965e2016-09-30 15:34:19 +00002237 }
2238
2239 assert(CurPhase < phases::Backend && "Generating single CUDA "
2240 "instructions should only occur "
2241 "before the backend phase!");
2242
2243 // By default, we produce an action for each device arch.
2244 for (Action *&A : CudaDeviceActions)
2245 A = C.getDriver().ConstructPhaseAction(C, Args, CurPhase, A);
2246
2247 return ABRT_Success;
2248 }
2249
2250 ActionBuilderReturnCode addDeviceDepences(Action *HostAction) override {
2251 // While generating code for CUDA, we only depend on the host input action
2252 // to trigger the creation of all the CUDA device actions.
2253
2254 // If we are dealing with an input action, replicate it for each GPU
2255 // architecture. If we are in host-only mode we return 'success' so that
2256 // the host uses the CUDA offload kind.
2257 if (auto *IA = dyn_cast<InputAction>(HostAction)) {
2258 assert(!GpuArchList.empty() &&
2259 "We should have at least one GPU architecture.");
2260
Yaxun Liu9809db72018-04-18 18:25:03 +00002261 // If the host input is not CUDA or HIP, we don't need to bother about
2262 // this input.
2263 if (IA->getType() != types::TY_CUDA &&
2264 IA->getType() != types::TY_HIP) {
Samuel Antao64e965e2016-09-30 15:34:19 +00002265 // The builder will ignore this input.
2266 IsActive = false;
2267 return ABRT_Inactive;
2268 }
2269
2270 // Set the flag to true, so that the builder acts on the current input.
2271 IsActive = true;
2272
2273 if (CompileHostOnly)
2274 return ABRT_Success;
2275
2276 // Replicate inputs for each GPU architecture.
Yaxun Liu9809db72018-04-18 18:25:03 +00002277 auto Ty = IA->getType() == types::TY_HIP ? types::TY_HIP_DEVICE
2278 : types::TY_CUDA_DEVICE;
2279 for (unsigned I = 0, E = GpuArchList.size(); I != E; ++I) {
2280 CudaDeviceActions.push_back(
2281 C.MakeAction<InputAction>(IA->getInputArg(), Ty));
2282 }
Samuel Antao64e965e2016-09-30 15:34:19 +00002283
2284 return ABRT_Success;
2285 }
2286
2287 return IsActive ? ABRT_Success : ABRT_Inactive;
2288 }
2289
2290 void appendTopLevelActions(ActionList &AL) override {
2291 // Utility to append actions to the top level list.
2292 auto AddTopLevel = [&](Action *A, CudaArch BoundArch) {
2293 OffloadAction::DeviceDependences Dep;
2294 Dep.add(*A, *ToolChains.front(), CudaArchToString(BoundArch),
2295 Action::OFK_Cuda);
2296 AL.push_back(C.MakeAction<OffloadAction>(Dep, A->getType()));
2297 };
2298
2299 // If we have a fat binary, add it to the list.
2300 if (CudaFatBinary) {
2301 AddTopLevel(CudaFatBinary, CudaArch::UNKNOWN);
2302 CudaDeviceActions.clear();
2303 CudaFatBinary = nullptr;
2304 return;
2305 }
2306
2307 if (CudaDeviceActions.empty())
2308 return;
2309
2310 // If we have CUDA actions at this point, that's because we have a have
2311 // partial compilation, so we should have an action for each GPU
2312 // architecture.
2313 assert(CudaDeviceActions.size() == GpuArchList.size() &&
2314 "Expecting one action per GPU architecture.");
2315 assert(ToolChains.size() == 1 &&
2316 "Expecting to have a sing CUDA toolchain.");
2317 for (unsigned I = 0, E = GpuArchList.size(); I != E; ++I)
2318 AddTopLevel(CudaDeviceActions[I], GpuArchList[I]);
2319
2320 CudaDeviceActions.clear();
2321 }
2322
2323 bool initialize() override {
2324 // We don't need to support CUDA.
2325 if (!C.hasOffloadToolChain<Action::OFK_Cuda>())
2326 return false;
2327
2328 const ToolChain *HostTC = C.getSingleOffloadToolChain<Action::OFK_Host>();
2329 assert(HostTC && "No toolchain for host compilation.");
2330 if (HostTC->getTriple().isNVPTX()) {
2331 // We do not support targeting NVPTX for host compilation. Throw
2332 // an error and abort pipeline construction early so we don't trip
2333 // asserts that assume device-side compilation.
2334 C.getDriver().Diag(diag::err_drv_cuda_nvptx_host);
2335 return true;
2336 }
2337
2338 ToolChains.push_back(C.getSingleOffloadToolChain<Action::OFK_Cuda>());
2339
2340 Arg *PartialCompilationArg = Args.getLastArg(
2341 options::OPT_cuda_host_only, options::OPT_cuda_device_only,
2342 options::OPT_cuda_compile_host_device);
2343 CompileHostOnly = PartialCompilationArg &&
2344 PartialCompilationArg->getOption().matches(
2345 options::OPT_cuda_host_only);
2346 CompileDeviceOnly = PartialCompilationArg &&
2347 PartialCompilationArg->getOption().matches(
2348 options::OPT_cuda_device_only);
2349
2350 // Collect all cuda_gpu_arch parameters, removing duplicates.
Artem Belevicha424e882016-12-09 22:59:17 +00002351 std::set<CudaArch> GpuArchs;
Samuel Antao64e965e2016-09-30 15:34:19 +00002352 bool Error = false;
2353 for (Arg *A : Args) {
Artem Belevicha424e882016-12-09 22:59:17 +00002354 if (!(A->getOption().matches(options::OPT_cuda_gpu_arch_EQ) ||
2355 A->getOption().matches(options::OPT_no_cuda_gpu_arch_EQ)))
Samuel Antao64e965e2016-09-30 15:34:19 +00002356 continue;
2357 A->claim();
2358
Artem Belevicha424e882016-12-09 22:59:17 +00002359 const StringRef ArchStr = A->getValue();
2360 if (A->getOption().matches(options::OPT_no_cuda_gpu_arch_EQ) &&
2361 ArchStr == "all") {
2362 GpuArchs.clear();
2363 continue;
2364 }
Samuel Antao64e965e2016-09-30 15:34:19 +00002365 CudaArch Arch = StringToCudaArch(ArchStr);
2366 if (Arch == CudaArch::UNKNOWN) {
2367 C.getDriver().Diag(clang::diag::err_drv_cuda_bad_gpu_arch) << ArchStr;
2368 Error = true;
Artem Belevicha424e882016-12-09 22:59:17 +00002369 } else if (A->getOption().matches(options::OPT_cuda_gpu_arch_EQ))
2370 GpuArchs.insert(Arch);
2371 else if (A->getOption().matches(options::OPT_no_cuda_gpu_arch_EQ))
2372 GpuArchs.erase(Arch);
2373 else
2374 llvm_unreachable("Unexpected option.");
Samuel Antao64e965e2016-09-30 15:34:19 +00002375 }
2376
Artem Belevicha424e882016-12-09 22:59:17 +00002377 // Collect list of GPUs remaining in the set.
2378 for (CudaArch Arch : GpuArchs)
2379 GpuArchList.push_back(Arch);
2380
2381 // Default to sm_20 which is the lowest common denominator for
2382 // supported GPUs. sm_20 code should work correctly, if
2383 // suboptimally, on all newer GPUs.
Samuel Antao64e965e2016-09-30 15:34:19 +00002384 if (GpuArchList.empty())
2385 GpuArchList.push_back(CudaArch::SM_20);
2386
2387 return Error;
2388 }
2389 };
2390
Samuel Antao28c4f182016-10-27 17:08:03 +00002391 /// OpenMP action builder. The host bitcode is passed to the device frontend
2392 /// and all the device linked images are passed to the host link phase.
2393 class OpenMPActionBuilder final : public DeviceActionBuilder {
2394 /// The OpenMP actions for the current input.
2395 ActionList OpenMPDeviceActions;
2396
2397 /// The linker inputs obtained for each toolchain.
2398 SmallVector<ActionList, 8> DeviceLinkerInputs;
2399
2400 public:
2401 OpenMPActionBuilder(Compilation &C, DerivedArgList &Args,
2402 const Driver::InputList &Inputs)
2403 : DeviceActionBuilder(C, Args, Inputs, Action::OFK_OpenMP) {}
2404
2405 ActionBuilderReturnCode
2406 getDeviceDependences(OffloadAction::DeviceDependences &DA,
2407 phases::ID CurPhase, phases::ID FinalPhase,
2408 PhasesTy &Phases) override {
2409
2410 // We should always have an action for each input.
2411 assert(OpenMPDeviceActions.size() == ToolChains.size() &&
2412 "Number of OpenMP actions and toolchains do not match.");
2413
2414 // The host only depends on device action in the linking phase, when all
2415 // the device images have to be embedded in the host image.
2416 if (CurPhase == phases::Link) {
2417 assert(ToolChains.size() == DeviceLinkerInputs.size() &&
2418 "Toolchains and linker inputs sizes do not match.");
2419 auto LI = DeviceLinkerInputs.begin();
2420 for (auto *A : OpenMPDeviceActions) {
2421 LI->push_back(A);
2422 ++LI;
2423 }
2424
2425 // We passed the device action as a host dependence, so we don't need to
2426 // do anything else with them.
2427 OpenMPDeviceActions.clear();
2428 return ABRT_Success;
2429 }
2430
2431 // By default, we produce an action for each device arch.
2432 for (Action *&A : OpenMPDeviceActions)
2433 A = C.getDriver().ConstructPhaseAction(C, Args, CurPhase, A);
2434
2435 return ABRT_Success;
2436 }
2437
2438 ActionBuilderReturnCode addDeviceDepences(Action *HostAction) override {
2439
2440 // If this is an input action replicate it for each OpenMP toolchain.
2441 if (auto *IA = dyn_cast<InputAction>(HostAction)) {
2442 OpenMPDeviceActions.clear();
2443 for (unsigned I = 0; I < ToolChains.size(); ++I)
2444 OpenMPDeviceActions.push_back(
2445 C.MakeAction<InputAction>(IA->getInputArg(), IA->getType()));
2446 return ABRT_Success;
2447 }
2448
Samuel Antaofab4f372016-10-27 18:00:51 +00002449 // If this is an unbundling action use it as is for each OpenMP toolchain.
2450 if (auto *UA = dyn_cast<OffloadUnbundlingJobAction>(HostAction)) {
2451 OpenMPDeviceActions.clear();
2452 for (unsigned I = 0; I < ToolChains.size(); ++I) {
2453 OpenMPDeviceActions.push_back(UA);
2454 UA->registerDependentActionInfo(
2455 ToolChains[I], /*BoundArch=*/StringRef(), Action::OFK_OpenMP);
2456 }
2457 return ABRT_Success;
2458 }
2459
Samuel Antao28c4f182016-10-27 17:08:03 +00002460 // When generating code for OpenMP we use the host compile phase result as
2461 // a dependence to the device compile phase so that it can learn what
2462 // declarations should be emitted. However, this is not the only use for
2463 // the host action, so we prevent it from being collapsed.
2464 if (isa<CompileJobAction>(HostAction)) {
2465 HostAction->setCannotBeCollapsedWithNextDependentAction();
2466 assert(ToolChains.size() == OpenMPDeviceActions.size() &&
2467 "Toolchains and device action sizes do not match.");
2468 OffloadAction::HostDependence HDep(
2469 *HostAction, *C.getSingleOffloadToolChain<Action::OFK_Host>(),
2470 /*BoundArch=*/nullptr, Action::OFK_OpenMP);
2471 auto TC = ToolChains.begin();
2472 for (Action *&A : OpenMPDeviceActions) {
2473 assert(isa<CompileJobAction>(A));
2474 OffloadAction::DeviceDependences DDep;
2475 DDep.add(*A, **TC, /*BoundArch=*/nullptr, Action::OFK_OpenMP);
2476 A = C.MakeAction<OffloadAction>(HDep, DDep);
2477 ++TC;
2478 }
2479 }
2480 return ABRT_Success;
2481 }
2482
Samuel Antao69d6f312016-10-27 17:50:43 +00002483 void appendTopLevelActions(ActionList &AL) override {
2484 if (OpenMPDeviceActions.empty())
2485 return;
2486
2487 // We should always have an action for each input.
2488 assert(OpenMPDeviceActions.size() == ToolChains.size() &&
2489 "Number of OpenMP actions and toolchains do not match.");
2490
2491 // Append all device actions followed by the proper offload action.
2492 auto TI = ToolChains.begin();
2493 for (auto *A : OpenMPDeviceActions) {
2494 OffloadAction::DeviceDependences Dep;
2495 Dep.add(*A, **TI, /*BoundArch=*/nullptr, Action::OFK_OpenMP);
2496 AL.push_back(C.MakeAction<OffloadAction>(Dep, A->getType()));
2497 ++TI;
2498 }
2499 // We no longer need the action stored in this builder.
2500 OpenMPDeviceActions.clear();
2501 }
2502
Samuel Antao28c4f182016-10-27 17:08:03 +00002503 void appendLinkDependences(OffloadAction::DeviceDependences &DA) override {
2504 assert(ToolChains.size() == DeviceLinkerInputs.size() &&
2505 "Toolchains and linker inputs sizes do not match.");
2506
2507 // Append a new link action for each device.
2508 auto TC = ToolChains.begin();
2509 for (auto &LI : DeviceLinkerInputs) {
2510 auto *DeviceLinkAction =
2511 C.MakeAction<LinkJobAction>(LI, types::TY_Image);
2512 DA.add(*DeviceLinkAction, **TC, /*BoundArch=*/nullptr,
2513 Action::OFK_OpenMP);
2514 ++TC;
2515 }
2516 }
2517
2518 bool initialize() override {
2519 // Get the OpenMP toolchains. If we don't get any, the action builder will
2520 // know there is nothing to do related to OpenMP offloading.
2521 auto OpenMPTCRange = C.getOffloadToolChains<Action::OFK_OpenMP>();
2522 for (auto TI = OpenMPTCRange.first, TE = OpenMPTCRange.second; TI != TE;
2523 ++TI)
2524 ToolChains.push_back(TI->second);
2525
2526 DeviceLinkerInputs.resize(ToolChains.size());
2527 return false;
2528 }
Samuel Antao69d6f312016-10-27 17:50:43 +00002529
2530 bool canUseBundlerUnbundler() const override {
2531 // OpenMP should use bundled files whenever possible.
2532 return true;
2533 }
Samuel Antao28c4f182016-10-27 17:08:03 +00002534 };
2535
2536 ///
2537 /// TODO: Add the implementation for other specialized builders here.
2538 ///
Samuel Antao64e965e2016-09-30 15:34:19 +00002539
2540 /// Specialized builders being used by this offloading action builder.
2541 SmallVector<DeviceActionBuilder *, 4> SpecializedBuilders;
2542
Samuel Antao69d6f312016-10-27 17:50:43 +00002543 /// Flag set to true if all valid builders allow file bundling/unbundling.
2544 bool CanUseBundler;
2545
Samuel Antao64e965e2016-09-30 15:34:19 +00002546public:
2547 OffloadingActionBuilder(Compilation &C, DerivedArgList &Args,
2548 const Driver::InputList &Inputs)
Samuel Antao10e905c2016-10-27 01:08:58 +00002549 : C(C) {
Samuel Antao64e965e2016-09-30 15:34:19 +00002550 // Create a specialized builder for each device toolchain.
2551
2552 IsValid = true;
2553
2554 // Create a specialized builder for CUDA.
2555 SpecializedBuilders.push_back(new CudaActionBuilder(C, Args, Inputs));
2556
Samuel Antao28c4f182016-10-27 17:08:03 +00002557 // Create a specialized builder for OpenMP.
2558 SpecializedBuilders.push_back(new OpenMPActionBuilder(C, Args, Inputs));
2559
Samuel Antao64e965e2016-09-30 15:34:19 +00002560 //
2561 // TODO: Build other specialized builders here.
2562 //
2563
Samuel Antao69d6f312016-10-27 17:50:43 +00002564 // Initialize all the builders, keeping track of errors. If all valid
2565 // builders agree that we can use bundling, set the flag to true.
2566 unsigned ValidBuilders = 0u;
2567 unsigned ValidBuildersSupportingBundling = 0u;
2568 for (auto *SB : SpecializedBuilders) {
Samuel Antao64e965e2016-09-30 15:34:19 +00002569 IsValid = IsValid && !SB->initialize();
Samuel Antao69d6f312016-10-27 17:50:43 +00002570
2571 // Update the counters if the builder is valid.
2572 if (SB->isValid()) {
2573 ++ValidBuilders;
2574 if (SB->canUseBundlerUnbundler())
2575 ++ValidBuildersSupportingBundling;
2576 }
2577 }
2578 CanUseBundler =
2579 ValidBuilders && ValidBuilders == ValidBuildersSupportingBundling;
Artem Belevichf981e30b2016-08-02 22:37:47 +00002580 }
Justin Lebardc3c5042016-04-19 02:27:07 +00002581
Samuel Antao64e965e2016-09-30 15:34:19 +00002582 ~OffloadingActionBuilder() {
2583 for (auto *SB : SpecializedBuilders)
2584 delete SB;
Samuel Antaod06239d2016-07-15 23:13:27 +00002585 }
Artem Belevich0ff05cd2015-07-13 23:27:56 +00002586
Samuel Antao64e965e2016-09-30 15:34:19 +00002587 /// Generate an action that adds device dependences (if any) to a host action.
2588 /// If no device dependence actions exist, just return the host action \a
2589 /// HostAction. If an error is found or if no builder requires the host action
2590 /// to be generated, return nullptr.
2591 Action *
2592 addDeviceDependencesToHostAction(Action *HostAction, const Arg *InputArg,
2593 phases::ID CurPhase, phases::ID FinalPhase,
2594 DeviceActionBuilder::PhasesTy &Phases) {
2595 if (!IsValid)
2596 return nullptr;
Justin Lebar7bf77982016-01-11 23:27:13 +00002597
Samuel Antao64e965e2016-09-30 15:34:19 +00002598 if (SpecializedBuilders.empty())
2599 return HostAction;
2600
2601 assert(HostAction && "Invalid host action!");
2602
2603 OffloadAction::DeviceDependences DDeps;
2604 // Check if all the programming models agree we should not emit the host
2605 // action. Also, keep track of the offloading kinds employed.
2606 auto &OffloadKind = InputArgToOffloadKindMap[InputArg];
2607 unsigned InactiveBuilders = 0u;
2608 unsigned IgnoringBuilders = 0u;
2609 for (auto *SB : SpecializedBuilders) {
2610 if (!SB->isValid()) {
2611 ++InactiveBuilders;
2612 continue;
2613 }
2614
Samuel Antao28c4f182016-10-27 17:08:03 +00002615 auto RetCode =
2616 SB->getDeviceDependences(DDeps, CurPhase, FinalPhase, Phases);
Samuel Antao64e965e2016-09-30 15:34:19 +00002617
2618 // If the builder explicitly says the host action should be ignored,
2619 // we need to increment the variable that tracks the builders that request
2620 // the host object to be ignored.
2621 if (RetCode == DeviceActionBuilder::ABRT_Ignore_Host)
2622 ++IgnoringBuilders;
2623
2624 // Unless the builder was inactive for this action, we have to record the
2625 // offload kind because the host will have to use it.
2626 if (RetCode != DeviceActionBuilder::ABRT_Inactive)
2627 OffloadKind |= SB->getAssociatedOffloadKind();
2628 }
2629
2630 // If all builders agree that the host object should be ignored, just return
2631 // nullptr.
2632 if (IgnoringBuilders &&
2633 SpecializedBuilders.size() == (InactiveBuilders + IgnoringBuilders))
2634 return nullptr;
2635
2636 if (DDeps.getActions().empty())
2637 return HostAction;
2638
2639 // We have dependences we need to bundle together. We use an offload action
2640 // for that.
2641 OffloadAction::HostDependence HDep(
2642 *HostAction, *C.getSingleOffloadToolChain<Action::OFK_Host>(),
2643 /*BoundArch=*/nullptr, DDeps);
2644 return C.MakeAction<OffloadAction>(HDep, DDeps);
Artem Belevich0ff05cd2015-07-13 23:27:56 +00002645 }
2646
Samuel Antao64e965e2016-09-30 15:34:19 +00002647 /// Generate an action that adds a host dependence to a device action. The
2648 /// results will be kept in this action builder. Return true if an error was
2649 /// found.
Samuel Antaofab4f372016-10-27 18:00:51 +00002650 bool addHostDependenceToDeviceActions(Action *&HostAction,
Samuel Antao64e965e2016-09-30 15:34:19 +00002651 const Arg *InputArg) {
2652 if (!IsValid)
2653 return true;
Artem Belevich0ff05cd2015-07-13 23:27:56 +00002654
Samuel Antaofab4f372016-10-27 18:00:51 +00002655 // If we are supporting bundling/unbundling and the current action is an
2656 // input action of non-source file, we replace the host action by the
2657 // unbundling action. The bundler tool has the logic to detect if an input
2658 // is a bundle or not and if the input is not a bundle it assumes it is a
2659 // host file. Therefore it is safe to create an unbundling action even if
2660 // the input is not a bundle.
2661 if (CanUseBundler && isa<InputAction>(HostAction) &&
2662 InputArg->getOption().getKind() == llvm::opt::Option::InputClass &&
2663 !types::isSrcFile(HostAction->getType())) {
2664 auto UnbundlingHostAction =
2665 C.MakeAction<OffloadUnbundlingJobAction>(HostAction);
2666 UnbundlingHostAction->registerDependentActionInfo(
2667 C.getSingleOffloadToolChain<Action::OFK_Host>(),
2668 /*BoundArch=*/StringRef(), Action::OFK_Host);
2669 HostAction = UnbundlingHostAction;
2670 }
2671
Samuel Antao64e965e2016-09-30 15:34:19 +00002672 assert(HostAction && "Invalid host action!");
Artem Belevich0ff05cd2015-07-13 23:27:56 +00002673
Samuel Antao64e965e2016-09-30 15:34:19 +00002674 // Register the offload kinds that are used.
2675 auto &OffloadKind = InputArgToOffloadKindMap[InputArg];
2676 for (auto *SB : SpecializedBuilders) {
2677 if (!SB->isValid())
2678 continue;
Artem Belevich0ff05cd2015-07-13 23:27:56 +00002679
Samuel Antao64e965e2016-09-30 15:34:19 +00002680 auto RetCode = SB->addDeviceDepences(HostAction);
Artem Belevich0ff05cd2015-07-13 23:27:56 +00002681
Samuel Antao64e965e2016-09-30 15:34:19 +00002682 // Host dependences for device actions are not compatible with that same
2683 // action being ignored.
2684 assert(RetCode != DeviceActionBuilder::ABRT_Ignore_Host &&
2685 "Host dependence not expected to be ignored.!");
Samuel Antaod06239d2016-07-15 23:13:27 +00002686
Samuel Antao64e965e2016-09-30 15:34:19 +00002687 // Unless the builder was inactive for this action, we have to record the
2688 // offload kind because the host will have to use it.
2689 if (RetCode != DeviceActionBuilder::ABRT_Inactive)
2690 OffloadKind |= SB->getAssociatedOffloadKind();
2691 }
Artem Belevich0ff05cd2015-07-13 23:27:56 +00002692
Samuel Antao64e965e2016-09-30 15:34:19 +00002693 return false;
2694 }
2695
Samuel Antao69d6f312016-10-27 17:50:43 +00002696 /// Add the offloading top level actions to the provided action list. This
2697 /// function can replace the host action by a bundling action if the
2698 /// programming models allow it.
Samuel Antao64e965e2016-09-30 15:34:19 +00002699 bool appendTopLevelActions(ActionList &AL, Action *HostAction,
2700 const Arg *InputArg) {
Samuel Antao69d6f312016-10-27 17:50:43 +00002701 // Get the device actions to be appended.
2702 ActionList OffloadAL;
Samuel Antao64e965e2016-09-30 15:34:19 +00002703 for (auto *SB : SpecializedBuilders) {
2704 if (!SB->isValid())
2705 continue;
Samuel Antao69d6f312016-10-27 17:50:43 +00002706 SB->appendTopLevelActions(OffloadAL);
Samuel Antao64e965e2016-09-30 15:34:19 +00002707 }
2708
Samuel Antao69d6f312016-10-27 17:50:43 +00002709 // If we can use the bundler, replace the host action by the bundling one in
2710 // the resulting list. Otherwise, just append the device actions.
2711 if (CanUseBundler && !OffloadAL.empty()) {
2712 // Add the host action to the list in order to create the bundling action.
2713 OffloadAL.push_back(HostAction);
2714
2715 // We expect that the host action was just appended to the action list
2716 // before this method was called.
2717 assert(HostAction == AL.back() && "Host action not in the list??");
2718 HostAction = C.MakeAction<OffloadBundlingJobAction>(OffloadAL);
2719 AL.back() = HostAction;
2720 } else
2721 AL.append(OffloadAL.begin(), OffloadAL.end());
2722
Samuel Antao64e965e2016-09-30 15:34:19 +00002723 // Propagate to the current host action (if any) the offload information
2724 // associated with the current input.
2725 if (HostAction)
2726 HostAction->propagateHostOffloadInfo(InputArgToOffloadKindMap[InputArg],
2727 /*BoundArch=*/nullptr);
Samuel Antao64e965e2016-09-30 15:34:19 +00002728 return false;
Artem Belevich0ff05cd2015-07-13 23:27:56 +00002729 }
Artem Belevich5bde4e02015-07-20 20:02:54 +00002730
Samuel Antao64e965e2016-09-30 15:34:19 +00002731 /// Processes the host linker action. This currently consists of replacing it
2732 /// with an offload action if there are device link objects and propagate to
2733 /// the host action all the offload kinds used in the current compilation. The
2734 /// resulting action is returned.
2735 Action *processHostLinkAction(Action *HostAction) {
2736 // Add all the dependences from the device linking actions.
2737 OffloadAction::DeviceDependences DDeps;
2738 for (auto *SB : SpecializedBuilders) {
2739 if (!SB->isValid())
2740 continue;
Justin Lebar21e5d4f2016-01-14 21:41:27 +00002741
Samuel Antao64e965e2016-09-30 15:34:19 +00002742 SB->appendLinkDependences(DDeps);
Justin Lebar21e5d4f2016-01-14 21:41:27 +00002743 }
Samuel Antaod06239d2016-07-15 23:13:27 +00002744
Samuel Antao64e965e2016-09-30 15:34:19 +00002745 // Calculate all the offload kinds used in the current compilation.
2746 unsigned ActiveOffloadKinds = 0u;
2747 for (auto &I : InputArgToOffloadKindMap)
2748 ActiveOffloadKinds |= I.second;
2749
2750 // If we don't have device dependencies, we don't have to create an offload
2751 // action.
2752 if (DDeps.getActions().empty()) {
2753 // Propagate all the active kinds to host action. Given that it is a link
2754 // action it is assumed to depend on all actions generated so far.
2755 HostAction->propagateHostOffloadInfo(ActiveOffloadKinds,
2756 /*BoundArch=*/nullptr);
2757 return HostAction;
2758 }
2759
2760 // Create the offload action with all dependences. When an offload action
2761 // is created the kinds are propagated to the host action, so we don't have
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00002762 // to do that explicitly here.
Samuel Antao64e965e2016-09-30 15:34:19 +00002763 OffloadAction::HostDependence HDep(
2764 *HostAction, *C.getSingleOffloadToolChain<Action::OFK_Host>(),
2765 /*BoundArch*/ nullptr, ActiveOffloadKinds);
2766 return C.MakeAction<OffloadAction>(HDep, DDeps);
2767 }
2768};
2769} // anonymous namespace.
Artem Belevich0ff05cd2015-07-13 23:27:56 +00002770
Justin Lebar0f3474c2016-02-11 02:00:50 +00002771void Driver::BuildActions(Compilation &C, DerivedArgList &Args,
2772 const InputList &Inputs, ActionList &Actions) const {
Chad Rosierecdede82011-08-12 22:08:57 +00002773 llvm::PrettyStackTraceString CrashInfo("Building compilation actions");
Joerg Sonnenbergerb86f5f42011-03-06 23:31:01 +00002774
Daniel Dunbar34c41872009-03-13 00:17:48 +00002775 if (!SuppressMissingInputWarning && Inputs.empty()) {
Daniel Dunbarbfeec742009-03-12 23:55:14 +00002776 Diag(clang::diag::err_drv_no_input_files);
2777 return;
2778 }
2779
Chad Rosier7742b5d2011-07-27 23:36:45 +00002780 Arg *FinalPhaseArg;
2781 phases::ID FinalPhase = getFinalPhase(Args, &FinalPhaseArg);
Daniel Dunbarbfeec742009-03-12 23:55:14 +00002782
Bob Haarmanaaf51912017-02-27 19:40:19 +00002783 if (FinalPhase == phases::Link) {
2784 if (Args.hasArg(options::OPT_emit_llvm))
2785 Diag(clang::diag::err_drv_emit_llvm_link);
2786 if (IsCLMode() && LTOMode != LTOK_None &&
2787 !Args.getLastArgValue(options::OPT_fuse_ld_EQ).equals_lower("lld"))
2788 Diag(clang::diag::err_drv_lto_without_lld);
Rafael Espindolae8025642013-08-25 14:27:09 +00002789 }
2790
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00002791 // Reject -Z* at the top level, these options should never have been exposed
2792 // by gcc.
Daniel Dunbardd765242009-03-26 16:12:09 +00002793 if (Arg *A = Args.getLastArg(options::OPT_Z_Joined))
Daniel Dunbar0e759942009-03-20 06:14:23 +00002794 Diag(clang::diag::err_drv_use_of_Z_option) << A->getAsString(Args);
Daniel Dunbarbfeec742009-03-12 23:55:14 +00002795
Hans Wennborg13b7fe72013-08-12 23:26:25 +00002796 // Diagnose misuse of /Fo.
2797 if (Arg *A = Args.getLastArg(options::OPT__SLASH_Fo)) {
Hans Wennborg13b7fe72013-08-12 23:26:25 +00002798 StringRef V = A->getValue();
Hans Wennborg61647532014-11-17 19:16:36 +00002799 if (Inputs.size() > 1 && !V.empty() &&
2800 !llvm::sys::path::is_separator(V.back())) {
Hans Wennborg13b7fe72013-08-12 23:26:25 +00002801 // Check whether /Fo tries to name an output file for multiple inputs.
Hans Wennborg9c1659b2013-10-18 22:49:04 +00002802 Diag(clang::diag::err_drv_out_file_argument_with_multiple_sources)
Douglas Katzmana67e50c2015-06-26 15:47:46 +00002803 << A->getSpelling() << V;
Hans Wennborg13b7fe72013-08-12 23:26:25 +00002804 Args.eraseArg(options::OPT__SLASH_Fo);
2805 }
2806 }
2807
Hans Wennborg9c1659b2013-10-18 22:49:04 +00002808 // Diagnose misuse of /Fa.
2809 if (Arg *A = Args.getLastArg(options::OPT__SLASH_Fa)) {
2810 StringRef V = A->getValue();
Hans Wennborg61647532014-11-17 19:16:36 +00002811 if (Inputs.size() > 1 && !V.empty() &&
2812 !llvm::sys::path::is_separator(V.back())) {
Hans Wennborg9c1659b2013-10-18 22:49:04 +00002813 // Check whether /Fa tries to name an asm file for multiple inputs.
2814 Diag(clang::diag::err_drv_out_file_argument_with_multiple_sources)
Douglas Katzmana67e50c2015-06-26 15:47:46 +00002815 << A->getSpelling() << V;
Hans Wennborg9c1659b2013-10-18 22:49:04 +00002816 Args.eraseArg(options::OPT__SLASH_Fa);
2817 }
2818 }
2819
Ehsan Akhgari81f36b72014-09-11 18:16:21 +00002820 // Diagnose misuse of /o.
2821 if (Arg *A = Args.getLastArg(options::OPT__SLASH_o)) {
2822 if (A->getValue()[0] == '\0') {
2823 // It has to have a value.
2824 Diag(clang::diag::err_drv_missing_argument) << A->getSpelling() << 1;
2825 Args.eraseArg(options::OPT__SLASH_o);
2826 }
2827 }
2828
Nico Weber2ca4be92016-03-01 23:16:44 +00002829 // Diagnose unsupported forms of /Yc /Yu. Ignore /Yc/Yu for now if:
2830 // * no filename after it
2831 // * both /Yc and /Yu passed but with different filenames
2832 // * corresponding file not also passed as /FI
2833 Arg *YcArg = Args.getLastArg(options::OPT__SLASH_Yc);
2834 Arg *YuArg = Args.getLastArg(options::OPT__SLASH_Yu);
2835 if (YcArg && YcArg->getValue()[0] == '\0') {
2836 Diag(clang::diag::warn_drv_ycyu_no_arg_clang_cl) << YcArg->getSpelling();
2837 Args.eraseArg(options::OPT__SLASH_Yc);
2838 YcArg = nullptr;
2839 }
2840 if (YuArg && YuArg->getValue()[0] == '\0') {
2841 Diag(clang::diag::warn_drv_ycyu_no_arg_clang_cl) << YuArg->getSpelling();
2842 Args.eraseArg(options::OPT__SLASH_Yu);
2843 YuArg = nullptr;
2844 }
2845 if (YcArg && YuArg && strcmp(YcArg->getValue(), YuArg->getValue()) != 0) {
2846 Diag(clang::diag::warn_drv_ycyu_different_arg_clang_cl);
2847 Args.eraseArg(options::OPT__SLASH_Yc);
2848 Args.eraseArg(options::OPT__SLASH_Yu);
2849 YcArg = YuArg = nullptr;
2850 }
2851 if (YcArg || YuArg) {
2852 StringRef Val = YcArg ? YcArg->getValue() : YuArg->getValue();
2853 bool FoundMatchingInclude = false;
2854 for (const Arg *Inc : Args.filtered(options::OPT_include)) {
2855 // FIXME: Do case-insensitive matching and consider / and \ as equal.
2856 if (Inc->getValue() == Val)
2857 FoundMatchingInclude = true;
2858 }
2859 if (!FoundMatchingInclude) {
2860 Diag(clang::diag::warn_drv_ycyu_no_fi_arg_clang_cl)
2861 << (YcArg ? YcArg : YuArg)->getSpelling();
2862 Args.eraseArg(options::OPT__SLASH_Yc);
2863 Args.eraseArg(options::OPT__SLASH_Yu);
2864 YcArg = YuArg = nullptr;
2865 }
2866 }
2867 if (YcArg && Inputs.size() > 1) {
2868 Diag(clang::diag::warn_drv_yc_multiple_inputs_clang_cl);
2869 Args.eraseArg(options::OPT__SLASH_Yc);
2870 YcArg = nullptr;
2871 }
2872 if (Args.hasArg(options::OPT__SLASH_Y_)) {
2873 // /Y- disables all pch handling. Rather than check for it everywhere,
2874 // just remove clang-cl pch-related flags here.
2875 Args.eraseArg(options::OPT__SLASH_Fp);
2876 Args.eraseArg(options::OPT__SLASH_Yc);
2877 Args.eraseArg(options::OPT__SLASH_Yu);
2878 YcArg = YuArg = nullptr;
2879 }
Nico Weber2ca4be92016-03-01 23:16:44 +00002880
Samuel Antao64e965e2016-09-30 15:34:19 +00002881 // Builder to be used to build offloading actions.
2882 OffloadingActionBuilder OffloadBuilder(C, Args, Inputs);
Samuel Antaod06239d2016-07-15 23:13:27 +00002883
Daniel Dunbar65229332009-03-13 11:38:42 +00002884 // Construct the actions to perform.
2885 ActionList LinkerInputs;
Alp Toker965f8822013-11-27 05:22:15 +00002886
Matthew Curtis7ab8b2b2013-03-07 12:32:26 +00002887 llvm::SmallVector<phases::ID, phases::MaxNumberOfPhases> PL;
Artem Belevich5bde4e02015-07-20 20:02:54 +00002888 for (auto &I : Inputs) {
2889 types::ID InputType = I.first;
2890 const Arg *InputArg = I.second;
Daniel Dunbar65229332009-03-13 11:38:42 +00002891
Matthew Curtis7ab8b2b2013-03-07 12:32:26 +00002892 PL.clear();
2893 types::getCompilationPhases(InputType, PL);
Daniel Dunbar65229332009-03-13 11:38:42 +00002894
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00002895 // If the first step comes after the final phase we are doing as part of
2896 // this compilation, warn the user about it.
Matthew Curtis7ab8b2b2013-03-07 12:32:26 +00002897 phases::ID InitialPhase = PL[0];
Daniel Dunbar65229332009-03-13 11:38:42 +00002898 if (InitialPhase > FinalPhase) {
Daniel Dunbaradc5c7c2009-03-19 07:57:08 +00002899 // Claim here to avoid the more general unused warning.
2900 InputArg->claim();
Daniel Dunbar07806ca2009-09-17 04:13:26 +00002901
Daniel Dunbar2db3e732011-04-20 15:44:48 +00002902 // Suppress all unused style warnings with -Qunused-arguments
2903 if (Args.hasArg(options::OPT_Qunused_arguments))
2904 continue;
2905
Richard Smith403f76e2012-08-06 04:09:06 +00002906 // Special case when final phase determined by binary name, rather than
2907 // by a command-line argument with a corresponding Arg.
Hans Wennborg70850d82013-07-18 20:29:38 +00002908 if (CCCIsCPP())
Richard Smith403f76e2012-08-06 04:09:06 +00002909 Diag(clang::diag::warn_drv_input_file_unused_by_cpp)
Douglas Katzmana67e50c2015-06-26 15:47:46 +00002910 << InputArg->getAsString(Args) << getPhaseName(InitialPhase);
Daniel Dunbar07806ca2009-09-17 04:13:26 +00002911 // Special case '-E' warning on a previously preprocessed file to make
2912 // more sense.
Richard Smith403f76e2012-08-06 04:09:06 +00002913 else if (InitialPhase == phases::Compile &&
2914 FinalPhase == phases::Preprocess &&
2915 getPreprocessedType(InputType) == types::TY_INVALID)
Daniel Dunbar07806ca2009-09-17 04:13:26 +00002916 Diag(clang::diag::warn_drv_preprocessed_input_file_unused)
Douglas Katzmana67e50c2015-06-26 15:47:46 +00002917 << InputArg->getAsString(Args) << !!FinalPhaseArg
2918 << (FinalPhaseArg ? FinalPhaseArg->getOption().getName() : "");
Daniel Dunbar07806ca2009-09-17 04:13:26 +00002919 else
2920 Diag(clang::diag::warn_drv_input_file_unused)
Douglas Katzmana67e50c2015-06-26 15:47:46 +00002921 << InputArg->getAsString(Args) << getPhaseName(InitialPhase)
2922 << !!FinalPhaseArg
2923 << (FinalPhaseArg ? FinalPhaseArg->getOption().getName() : "");
Daniel Dunbar65229332009-03-13 11:38:42 +00002924 continue;
2925 }
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00002926
Nico Weberad2d8f32016-04-21 19:59:10 +00002927 if (YcArg) {
2928 // Add a separate precompile phase for the compile phase.
2929 if (FinalPhase >= phases::Compile) {
Richard Smith8cd452d2016-08-30 18:55:16 +00002930 const types::ID HeaderType = lookupHeaderTypeForSourceType(InputType);
Nico Weberad2d8f32016-04-21 19:59:10 +00002931 llvm::SmallVector<phases::ID, phases::MaxNumberOfPhases> PCHPL;
Richard Smith8cd452d2016-08-30 18:55:16 +00002932 types::getCompilationPhases(HeaderType, PCHPL);
David Blaikie0aaa7622017-01-13 17:34:15 +00002933 Arg *PchInputArg = MakeInputArg(Args, *Opts, YcArg->getValue());
Nico Weberad2d8f32016-04-21 19:59:10 +00002934
2935 // Build the pipeline for the pch file.
Richard Smith8cd452d2016-08-30 18:55:16 +00002936 Action *ClangClPch =
2937 C.MakeAction<InputAction>(*PchInputArg, HeaderType);
Nico Weberad2d8f32016-04-21 19:59:10 +00002938 for (phases::ID Phase : PCHPL)
2939 ClangClPch = ConstructPhaseAction(C, Args, Phase, ClangClPch);
2940 assert(ClangClPch);
2941 Actions.push_back(ClangClPch);
2942 // The driver currently exits after the first failed command. This
2943 // relies on that behavior, to make sure if the pch generation fails,
2944 // the main compilation won't run.
2945 }
2946 }
2947
Daniel Dunbar65229332009-03-13 11:38:42 +00002948 // Build the pipeline for this file.
Justin Lebar41094612016-01-11 23:07:27 +00002949 Action *Current = C.MakeAction<InputAction>(*InputArg, InputType);
Samuel Antao64e965e2016-09-30 15:34:19 +00002950
2951 // Use the current host action in any of the offloading actions, if
2952 // required.
2953 if (OffloadBuilder.addHostDependenceToDeviceActions(Current, InputArg))
2954 break;
2955
Douglas Katzmana67e50c2015-06-26 15:47:46 +00002956 for (SmallVectorImpl<phases::ID>::iterator i = PL.begin(), e = PL.end();
2957 i != e; ++i) {
Matthew Curtis7ab8b2b2013-03-07 12:32:26 +00002958 phases::ID Phase = *i;
Daniel Dunbar65229332009-03-13 11:38:42 +00002959
2960 // We are done if this step is past what the user requested.
2961 if (Phase > FinalPhase)
2962 break;
2963
Samuel Antao64e965e2016-09-30 15:34:19 +00002964 // Add any offload action the host action depends on.
2965 Current = OffloadBuilder.addDeviceDependencesToHostAction(
2966 Current, InputArg, Phase, FinalPhase, PL);
2967 if (!Current)
2968 break;
2969
Daniel Dunbar65229332009-03-13 11:38:42 +00002970 // Queue linker inputs.
2971 if (Phase == phases::Link) {
Matthew Curtis7ab8b2b2013-03-07 12:32:26 +00002972 assert((i + 1) == e && "linking must be final compilation step.");
Justin Lebar41094612016-01-11 23:07:27 +00002973 LinkerInputs.push_back(Current);
2974 Current = nullptr;
Daniel Dunbar65229332009-03-13 11:38:42 +00002975 break;
2976 }
2977
Samuel Antao64e965e2016-09-30 15:34:19 +00002978 // Otherwise construct the appropriate action.
2979 auto *NewCurrent = ConstructPhaseAction(C, Args, Phase, Current);
2980
2981 // We didn't create a new action, so we will just move to the next phase.
2982 if (NewCurrent == Current)
Daniel Dunbar13864952009-03-24 20:17:30 +00002983 continue;
2984
Samuel Antao64e965e2016-09-30 15:34:19 +00002985 Current = NewCurrent;
Artem Belevich0ff05cd2015-07-13 23:27:56 +00002986
Samuel Antao64e965e2016-09-30 15:34:19 +00002987 // Use the current host action in any of the offloading actions, if
2988 // required.
2989 if (OffloadBuilder.addHostDependenceToDeviceActions(Current, InputArg))
2990 break;
Artem Belevich0ff05cd2015-07-13 23:27:56 +00002991
Daniel Dunbar65229332009-03-13 11:38:42 +00002992 if (Current->getType() == types::TY_Nothing)
2993 break;
2994 }
2995
Samuel Antao64e965e2016-09-30 15:34:19 +00002996 // If we ended with something, add to the output list.
2997 if (Current)
Justin Lebar41094612016-01-11 23:07:27 +00002998 Actions.push_back(Current);
Samuel Antao64e965e2016-09-30 15:34:19 +00002999
3000 // Add any top level actions generated for offloading.
3001 OffloadBuilder.appendTopLevelActions(Actions, Current, InputArg);
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00003002 }
Daniel Dunbar65229332009-03-13 11:38:42 +00003003
Samuel Antao64e965e2016-09-30 15:34:19 +00003004 // Add a link action if necessary.
Samuel Antaod06239d2016-07-15 23:13:27 +00003005 if (!LinkerInputs.empty()) {
Samuel Antao64e965e2016-09-30 15:34:19 +00003006 Action *LA = C.MakeAction<LinkJobAction>(LinkerInputs, types::TY_Image);
3007 LA = OffloadBuilder.processHostLinkAction(LA);
3008 Actions.push_back(LA);
Samuel Antaod06239d2016-07-15 23:13:27 +00003009 }
Daniel Dunbarc7a67b72009-12-22 23:19:32 +00003010
3011 // If we are linking, claim any options which are obviously only used for
3012 // compilation.
Hans Wennborga8ef14f2013-09-17 00:03:41 +00003013 if (FinalPhase == phases::Link && PL.size() == 1) {
Daniel Dunbarc7a67b72009-12-22 23:19:32 +00003014 Args.ClaimAllArgs(options::OPT_CompileOnly_Group);
Hans Wennborga8ef14f2013-09-17 00:03:41 +00003015 Args.ClaimAllArgs(options::OPT_cl_compile_Group);
3016 }
3017
3018 // Claim ignored clang-cl options.
3019 Args.ClaimAllArgs(options::OPT_cl_ignored_Group);
Artem Belevichbaae0932015-07-28 21:01:30 +00003020
Justin Lebardc3c5042016-04-19 02:27:07 +00003021 // Claim --cuda-host-only and --cuda-compile-host-device, which may be passed
3022 // to non-CUDA compilations and should not trigger warnings there.
Artem Belevichbaae0932015-07-28 21:01:30 +00003023 Args.ClaimAllArgs(options::OPT_cuda_host_only);
Justin Lebardc3c5042016-04-19 02:27:07 +00003024 Args.ClaimAllArgs(options::OPT_cuda_compile_host_device);
Daniel Dunbar65229332009-03-13 11:38:42 +00003025}
3026
Artem Belevichecb178b2018-03-21 22:22:59 +00003027Action *Driver::ConstructPhaseAction(
3028 Compilation &C, const ArgList &Args, phases::ID Phase, Action *Input,
3029 Action::OffloadKind TargetDeviceOffloadKind) const {
Daniel Dunbar2608c542009-03-18 01:38:48 +00003030 llvm::PrettyStackTraceString CrashInfo("Constructing phase actions");
Samuel Antao64e965e2016-09-30 15:34:19 +00003031
3032 // Some types skip the assembler phase (e.g., llvm-bc), but we can't
3033 // encode this in the steps because the intermediate type depends on
3034 // arguments. Just special case here.
3035 if (Phase == phases::Assemble && Input->getType() != types::TY_PP_Asm)
3036 return Input;
3037
Daniel Dunbar65229332009-03-13 11:38:42 +00003038 // Build the appropriate action.
3039 switch (Phase) {
Douglas Katzmana67e50c2015-06-26 15:47:46 +00003040 case phases::Link:
3041 llvm_unreachable("link action invalid here.");
Daniel Dunbar65229332009-03-13 11:38:42 +00003042 case phases::Preprocess: {
Daniel Dunbard67a3222009-03-30 06:36:42 +00003043 types::ID OutputTy;
3044 // -{M, MM} alter the output type.
Daniel Dunbar86aed7d2010-12-08 21:33:40 +00003045 if (Args.hasArg(options::OPT_M, options::OPT_MM)) {
Daniel Dunbard67a3222009-03-30 06:36:42 +00003046 OutputTy = types::TY_Dependencies;
3047 } else {
David Blaikie5d577a22012-06-29 22:03:56 +00003048 OutputTy = Input->getType();
3049 if (!Args.hasFlag(options::OPT_frewrite_includes,
Justin Bognerce8245b2014-06-24 08:01:01 +00003050 options::OPT_fno_rewrite_includes, false) &&
Richard Smith86a3ef52017-06-09 21:24:02 +00003051 !Args.hasFlag(options::OPT_frewrite_imports,
3052 options::OPT_fno_rewrite_imports, false) &&
Justin Bognerce8245b2014-06-24 08:01:01 +00003053 !CCGenDiagnostics)
David Blaikie5d577a22012-06-29 22:03:56 +00003054 OutputTy = types::getPreprocessedType(OutputTy);
Daniel Dunbard67a3222009-03-30 06:36:42 +00003055 assert(OutputTy != types::TY_INVALID &&
3056 "Cannot preprocess this input type!");
3057 }
Justin Lebar41094612016-01-11 23:07:27 +00003058 return C.MakeAction<PreprocessJobAction>(Input, OutputTy);
Daniel Dunbar65229332009-03-13 11:38:42 +00003059 }
Aaron Ballman1f10cc52012-07-31 01:21:00 +00003060 case phases::Precompile: {
Richard Smithdd4ad3d2016-08-30 19:06:26 +00003061 types::ID OutputTy = getPrecompiledType(Input->getType());
3062 assert(OutputTy != types::TY_INVALID &&
3063 "Cannot precompile this input type!");
Aaron Ballman1f10cc52012-07-31 01:21:00 +00003064 if (Args.hasArg(options::OPT_fsyntax_only)) {
3065 // Syntax checks should not emit a PCH file
3066 OutputTy = types::TY_Nothing;
3067 }
Justin Lebar41094612016-01-11 23:07:27 +00003068 return C.MakeAction<PrecompileJobAction>(Input, OutputTy);
Aaron Ballman1f10cc52012-07-31 01:21:00 +00003069 }
Daniel Dunbar65229332009-03-13 11:38:42 +00003070 case phases::Compile: {
David Blaikie486f4402014-08-29 07:25:23 +00003071 if (Args.hasArg(options::OPT_fsyntax_only))
Justin Lebar41094612016-01-11 23:07:27 +00003072 return C.MakeAction<CompileJobAction>(Input, types::TY_Nothing);
David Blaikie486f4402014-08-29 07:25:23 +00003073 if (Args.hasArg(options::OPT_rewrite_objc))
Justin Lebar41094612016-01-11 23:07:27 +00003074 return C.MakeAction<CompileJobAction>(Input, types::TY_RewrittenObjC);
David Blaikie486f4402014-08-29 07:25:23 +00003075 if (Args.hasArg(options::OPT_rewrite_legacy_objc))
Justin Lebar41094612016-01-11 23:07:27 +00003076 return C.MakeAction<CompileJobAction>(Input,
3077 types::TY_RewrittenLegacyObjC);
David Blaikie486f4402014-08-29 07:25:23 +00003078 if (Args.hasArg(options::OPT__analyze, options::OPT__analyze_auto))
Justin Lebar41094612016-01-11 23:07:27 +00003079 return C.MakeAction<AnalyzeJobAction>(Input, types::TY_Plist);
David Blaikie486f4402014-08-29 07:25:23 +00003080 if (Args.hasArg(options::OPT__migrate))
Justin Lebar41094612016-01-11 23:07:27 +00003081 return C.MakeAction<MigrateJobAction>(Input, types::TY_Remap);
David Blaikie486f4402014-08-29 07:25:23 +00003082 if (Args.hasArg(options::OPT_emit_ast))
Justin Lebar41094612016-01-11 23:07:27 +00003083 return C.MakeAction<CompileJobAction>(Input, types::TY_AST);
David Blaikie486f4402014-08-29 07:25:23 +00003084 if (Args.hasArg(options::OPT_module_file_info))
Justin Lebar41094612016-01-11 23:07:27 +00003085 return C.MakeAction<CompileJobAction>(Input, types::TY_ModuleFile);
David Blaikie486f4402014-08-29 07:25:23 +00003086 if (Args.hasArg(options::OPT_verify_pch))
Justin Lebar41094612016-01-11 23:07:27 +00003087 return C.MakeAction<VerifyPCHJobAction>(Input, types::TY_Nothing);
3088 return C.MakeAction<CompileJobAction>(Input, types::TY_LLVM_BC);
Bob Wilson23a55f12014-12-21 07:00:00 +00003089 }
3090 case phases::Backend: {
Artem Belevichecb178b2018-03-21 22:22:59 +00003091 if (isUsingLTO() && TargetDeviceOffloadKind == Action::OFK_None) {
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00003092 types::ID Output =
Douglas Katzmana67e50c2015-06-26 15:47:46 +00003093 Args.hasArg(options::OPT_S) ? types::TY_LTO_IR : types::TY_LTO_BC;
Justin Lebar41094612016-01-11 23:07:27 +00003094 return C.MakeAction<BackendJobAction>(Input, Output);
David Blaikie486f4402014-08-29 07:25:23 +00003095 }
3096 if (Args.hasArg(options::OPT_emit_llvm)) {
Shuxin Yang4b3c7ff2013-08-23 21:34:57 +00003097 types::ID Output =
Douglas Katzmana67e50c2015-06-26 15:47:46 +00003098 Args.hasArg(options::OPT_S) ? types::TY_LLVM_IR : types::TY_LLVM_BC;
Justin Lebar41094612016-01-11 23:07:27 +00003099 return C.MakeAction<BackendJobAction>(Input, Output);
Daniel Dunbar65229332009-03-13 11:38:42 +00003100 }
Justin Lebar41094612016-01-11 23:07:27 +00003101 return C.MakeAction<BackendJobAction>(Input, types::TY_PP_Asm);
Daniel Dunbar65229332009-03-13 11:38:42 +00003102 }
3103 case phases::Assemble:
Justin Lebar21e5d4f2016-01-14 21:41:27 +00003104 return C.MakeAction<AssembleJobAction>(std::move(Input), types::TY_Object);
Daniel Dunbar65229332009-03-13 11:38:42 +00003105 }
3106
David Blaikie83d382b2011-09-23 05:06:16 +00003107 llvm_unreachable("invalid phase in ConstructPhaseAction");
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00003108}
3109
Daniel Dunbarf0eddb82009-03-18 02:55:38 +00003110void Driver::BuildJobs(Compilation &C) const {
Daniel Dunbar2608c542009-03-18 01:38:48 +00003111 llvm::PrettyStackTraceString CrashInfo("Building compilation jobs");
Daniel Dunbare75d8342009-03-16 06:56:51 +00003112
3113 Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o);
3114
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00003115 // It is an error to provide a -o option if we are making multiple output
3116 // files.
Daniel Dunbare75d8342009-03-16 06:56:51 +00003117 if (FinalOutput) {
3118 unsigned NumOutputs = 0;
Saleem Abdulrasoolda3f4e52014-12-29 21:02:47 +00003119 for (const Action *A : C.getActions())
3120 if (A->getType() != types::TY_Nothing)
Daniel Dunbare75d8342009-03-16 06:56:51 +00003121 ++NumOutputs;
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00003122
Daniel Dunbare75d8342009-03-16 06:56:51 +00003123 if (NumOutputs > 1) {
3124 Diag(clang::diag::err_drv_output_argument_with_multiple_files);
Craig Topper92fc2df2014-05-17 16:56:41 +00003125 FinalOutput = nullptr;
Daniel Dunbare75d8342009-03-16 06:56:51 +00003126 }
3127 }
3128
Chad Rosier35767232013-04-30 22:01:21 +00003129 // Collect the list of architectures.
3130 llvm::StringSet<> ArchNames;
Saleem Abdulrasool688b6bc2014-12-29 19:01:36 +00003131 if (C.getDefaultToolChain().getTriple().isOSBinFormatMachO())
3132 for (const Arg *A : C.getArgs())
Chad Rosier35767232013-04-30 22:01:21 +00003133 if (A->getOption().matches(options::OPT_arch))
3134 ArchNames.insert(A->getValue());
Chad Rosier35767232013-04-30 22:01:21 +00003135
Justin Lebarb44f6fe2016-01-14 21:41:21 +00003136 // Set of (Action, canonical ToolChain triple) pairs we've built jobs for.
3137 std::map<std::pair<const Action *, std::string>, InputInfo> CachedResults;
Saleem Abdulrasool688b6bc2014-12-29 19:01:36 +00003138 for (Action *A : C.getActions()) {
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00003139 // If we are linking an image for multiple archs then the linker wants
3140 // -arch_multiple and -final_output <final image name>. Unfortunately, this
3141 // doesn't fit in cleanly because we have to pass this information down.
Daniel Dunbare75d8342009-03-16 06:56:51 +00003142 //
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00003143 // FIXME: This is a hack; find a cleaner way to integrate this into the
3144 // process.
Craig Topper92fc2df2014-05-17 16:56:41 +00003145 const char *LinkingOutput = nullptr;
Daniel Dunbardd765242009-03-26 16:12:09 +00003146 if (isa<LipoJobAction>(A)) {
Daniel Dunbare75d8342009-03-16 06:56:51 +00003147 if (FinalOutput)
Richard Smithbd55daf2012-11-01 04:30:05 +00003148 LinkingOutput = FinalOutput->getValue();
Daniel Dunbare75d8342009-03-16 06:56:51 +00003149 else
Hans Wennborga7707222015-01-09 17:38:53 +00003150 LinkingOutput = getDefaultImageName();
Daniel Dunbare75d8342009-03-16 06:56:51 +00003151 }
3152
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00003153 BuildJobsForAction(C, A, &C.getDefaultToolChain(),
Mehdi Aminic50b1a22016-10-07 21:27:26 +00003154 /*BoundArch*/ StringRef(),
Daniel Dunbare75d8342009-03-16 06:56:51 +00003155 /*AtTopLevel*/ true,
Chad Rosier35767232013-04-30 22:01:21 +00003156 /*MultipleArchs*/ ArchNames.size() > 1,
Samuel Antaod06239d2016-07-15 23:13:27 +00003157 /*LinkingOutput*/ LinkingOutput, CachedResults,
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003158 /*TargetDeviceOffloadKind*/ Action::OFK_None);
Daniel Dunbare75d8342009-03-16 06:56:51 +00003159 }
Daniel Dunbar3ce436d2009-03-16 06:42:30 +00003160
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00003161 // If the user passed -Qunused-arguments or there were errors, don't warn
3162 // about any unused arguments.
Argyrios Kyrtzidis31448a42010-11-18 21:47:07 +00003163 if (Diags.hasErrorOccurred() ||
Daniel Dunbara3cfbe32009-04-07 19:04:18 +00003164 C.getArgs().hasArg(options::OPT_Qunused_arguments))
Daniel Dunbard175d972009-03-18 18:03:46 +00003165 return;
3166
Daniel Dunbar58399ae2009-03-29 22:24:54 +00003167 // Claim -### here.
Douglas Katzmana67e50c2015-06-26 15:47:46 +00003168 (void)C.getArgs().hasArg(options::OPT__HASH_HASH_HASH);
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00003169
Nico Weber47bf5052016-04-25 21:15:49 +00003170 // Claim --driver-mode, --rsp-quoting, it was handled earlier.
Douglas Katzmana67e50c2015-06-26 15:47:46 +00003171 (void)C.getArgs().hasArg(options::OPT_driver_mode);
Nico Weber47bf5052016-04-25 21:15:49 +00003172 (void)C.getArgs().hasArg(options::OPT_rsp_quoting);
Hans Wennborg70850d82013-07-18 20:29:38 +00003173
Saleem Abdulrasool688b6bc2014-12-29 19:01:36 +00003174 for (Arg *A : C.getArgs()) {
Daniel Dunbar3ce436d2009-03-16 06:42:30 +00003175 // FIXME: It would be nice to be able to send the argument to the
David Blaikie9c902b52011-09-25 23:23:43 +00003176 // DiagnosticsEngine, so that extra values, position, and so on could be
3177 // printed.
Daniel Dunbar90dd6f42009-04-04 00:52:26 +00003178 if (!A->isClaimed()) {
Michael J. Spencer66e2b202012-10-19 22:37:06 +00003179 if (A->getOption().hasFlag(options::NoArgumentUnused))
Daniel Dunbara3cfbe32009-04-07 19:04:18 +00003180 continue;
3181
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00003182 // Suppress the warning automatically if this is just a flag, and it is an
3183 // instance of an argument we already claimed.
Daniel Dunbar90dd6f42009-04-04 00:52:26 +00003184 const Option &Opt = A->getOption();
Michael J. Spencerad3ccc32012-08-20 21:41:17 +00003185 if (Opt.getKind() == Option::FlagClass) {
Daniel Dunbar90dd6f42009-04-04 00:52:26 +00003186 bool DuplicateClaimed = false;
3187
Sean Silva14facf32015-06-09 01:57:17 +00003188 for (const Arg *AA : C.getArgs().filtered(&Opt)) {
3189 if (AA->isClaimed()) {
Daniel Dunbar90dd6f42009-04-04 00:52:26 +00003190 DuplicateClaimed = true;
3191 break;
3192 }
3193 }
3194
3195 if (DuplicateClaimed)
3196 continue;
3197 }
3198
Ehsan Akhgarid8518332016-01-25 21:14:52 +00003199 // In clang-cl, don't mention unknown arguments here since they have
3200 // already been warned about.
3201 if (!IsCLMode() || !A->getOption().matches(options::OPT_UNKNOWN))
3202 Diag(clang::diag::warn_drv_unused_argument)
3203 << A->getAsString(C.getArgs());
Daniel Dunbar90dd6f42009-04-04 00:52:26 +00003204 }
Daniel Dunbar3ce436d2009-03-16 06:42:30 +00003205 }
Daniel Dunbar95e6b192009-03-13 22:12:33 +00003206}
Daniel Dunbarc4343942010-02-03 03:07:56 +00003207
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00003208namespace {
3209/// Utility class to control the collapse of dependent actions and select the
3210/// tools accordingly.
3211class ToolSelector final {
3212 /// The tool chain this selector refers to.
3213 const ToolChain &TC;
Daniel Dunbarf9ff3502010-05-14 02:03:00 +00003214
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00003215 /// The compilation this selector refers to.
3216 const Compilation &C;
Samuel Antaod06239d2016-07-15 23:13:27 +00003217
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00003218 /// The base action this selector refers to.
3219 const JobAction *BaseAction;
Samuel Antaod06239d2016-07-15 23:13:27 +00003220
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00003221 /// Set to true if the current toolchain refers to host actions.
3222 bool IsHostSelector;
Samuel Antaod06239d2016-07-15 23:13:27 +00003223
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00003224 /// Set to true if save-temps and embed-bitcode functionalities are active.
3225 bool SaveTemps;
3226 bool EmbedBitcode;
3227
3228 /// Get previous dependent action or null if that does not exist. If
3229 /// \a CanBeCollapsed is false, that action must be legal to collapse or
3230 /// null will be returned.
3231 const JobAction *getPrevDependentAction(const ActionList &Inputs,
3232 ActionList &SavedOffloadAction,
3233 bool CanBeCollapsed = true) {
3234 // An option can be collapsed only if it has a single input.
3235 if (Inputs.size() != 1)
Craig Topper92fc2df2014-05-17 16:56:41 +00003236 return nullptr;
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00003237
3238 Action *CurAction = *Inputs.begin();
3239 if (CanBeCollapsed &&
3240 !CurAction->isCollapsingWithNextDependentActionLegal())
3241 return nullptr;
3242
3243 // If the input action is an offload action. Look through it and save any
3244 // offload action that can be dropped in the event of a collapse.
3245 if (auto *OA = dyn_cast<OffloadAction>(CurAction)) {
3246 // If the dependent action is a device action, we will attempt to collapse
3247 // only with other device actions. Otherwise, we would do the same but
3248 // with host actions only.
3249 if (!IsHostSelector) {
3250 if (OA->hasSingleDeviceDependence(/*DoNotConsiderHostActions=*/true)) {
3251 CurAction =
3252 OA->getSingleDeviceDependence(/*DoNotConsiderHostActions=*/true);
3253 if (CanBeCollapsed &&
3254 !CurAction->isCollapsingWithNextDependentActionLegal())
3255 return nullptr;
3256 SavedOffloadAction.push_back(OA);
3257 return dyn_cast<JobAction>(CurAction);
3258 }
3259 } else if (OA->hasHostDependence()) {
3260 CurAction = OA->getHostDependence();
3261 if (CanBeCollapsed &&
3262 !CurAction->isCollapsingWithNextDependentActionLegal())
3263 return nullptr;
3264 SavedOffloadAction.push_back(OA);
3265 return dyn_cast<JobAction>(CurAction);
3266 }
3267 return nullptr;
3268 }
3269
3270 return dyn_cast<JobAction>(CurAction);
3271 }
3272
3273 /// Return true if an assemble action can be collapsed.
3274 bool canCollapseAssembleAction() const {
3275 return TC.useIntegratedAs() && !SaveTemps &&
3276 !C.getArgs().hasArg(options::OPT_via_file_asm) &&
3277 !C.getArgs().hasArg(options::OPT__SLASH_FA) &&
3278 !C.getArgs().hasArg(options::OPT__SLASH_Fa);
3279 }
3280
3281 /// Return true if a preprocessor action can be collapsed.
3282 bool canCollapsePreprocessorAction() const {
3283 return !C.getArgs().hasArg(options::OPT_no_integrated_cpp) &&
3284 !C.getArgs().hasArg(options::OPT_traditional_cpp) && !SaveTemps &&
3285 !C.getArgs().hasArg(options::OPT_rewrite_objc);
3286 }
3287
3288 /// Struct that relates an action with the offload actions that would be
3289 /// collapsed with it.
3290 struct JobActionInfo final {
3291 /// The action this info refers to.
3292 const JobAction *JA = nullptr;
3293 /// The offload actions we need to take care off if this action is
3294 /// collapsed.
3295 ActionList SavedOffloadAction;
3296 };
3297
3298 /// Append collapsed offload actions from the give nnumber of elements in the
3299 /// action info array.
3300 static void AppendCollapsedOffloadAction(ActionList &CollapsedOffloadAction,
3301 ArrayRef<JobActionInfo> &ActionInfo,
3302 unsigned ElementNum) {
3303 assert(ElementNum <= ActionInfo.size() && "Invalid number of elements.");
3304 for (unsigned I = 0; I < ElementNum; ++I)
3305 CollapsedOffloadAction.append(ActionInfo[I].SavedOffloadAction.begin(),
3306 ActionInfo[I].SavedOffloadAction.end());
3307 }
3308
3309 /// Functions that attempt to perform the combining. They detect if that is
3310 /// legal, and if so they update the inputs \a Inputs and the offload action
3311 /// that were collapsed in \a CollapsedOffloadAction. A tool that deals with
3312 /// the combined action is returned. If the combining is not legal or if the
3313 /// tool does not exist, null is returned.
3314 /// Currently three kinds of collapsing are supported:
3315 /// - Assemble + Backend + Compile;
3316 /// - Assemble + Backend ;
3317 /// - Backend + Compile.
3318 const Tool *
3319 combineAssembleBackendCompile(ArrayRef<JobActionInfo> ActionInfo,
3320 const ActionList *&Inputs,
3321 ActionList &CollapsedOffloadAction) {
3322 if (ActionInfo.size() < 3 || !canCollapseAssembleAction())
3323 return nullptr;
3324 auto *AJ = dyn_cast<AssembleJobAction>(ActionInfo[0].JA);
3325 auto *BJ = dyn_cast<BackendJobAction>(ActionInfo[1].JA);
3326 auto *CJ = dyn_cast<CompileJobAction>(ActionInfo[2].JA);
3327 if (!AJ || !BJ || !CJ)
3328 return nullptr;
3329
3330 // Get compiler tool.
3331 const Tool *T = TC.SelectTool(*CJ);
3332 if (!T)
3333 return nullptr;
3334
Steven Wu574b0f22016-03-01 01:07:58 +00003335 // When using -fembed-bitcode, it is required to have the same tool (clang)
3336 // for both CompilerJA and BackendJA. Otherwise, combine two stages.
3337 if (EmbedBitcode) {
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00003338 const Tool *BT = TC.SelectTool(*BJ);
3339 if (BT == T)
3340 return nullptr;
Steven Wu574b0f22016-03-01 01:07:58 +00003341 }
Bob Wilson23a55f12014-12-21 07:00:00 +00003342
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00003343 if (!T->hasIntegratedAssembler())
Bob Wilson23a55f12014-12-21 07:00:00 +00003344 return nullptr;
Samuel Antaod06239d2016-07-15 23:13:27 +00003345
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00003346 Inputs = &CJ->getInputs();
3347 AppendCollapsedOffloadAction(CollapsedOffloadAction, ActionInfo,
3348 /*NumElements=*/3);
3349 return T;
3350 }
3351 const Tool *combineAssembleBackend(ArrayRef<JobActionInfo> ActionInfo,
3352 const ActionList *&Inputs,
3353 ActionList &CollapsedOffloadAction) {
3354 if (ActionInfo.size() < 2 || !canCollapseAssembleAction())
3355 return nullptr;
3356 auto *AJ = dyn_cast<AssembleJobAction>(ActionInfo[0].JA);
3357 auto *BJ = dyn_cast<BackendJobAction>(ActionInfo[1].JA);
3358 if (!AJ || !BJ)
3359 return nullptr;
3360
3361 // Retrieve the compile job, backend action must always be preceded by one.
3362 ActionList CompileJobOffloadActions;
3363 auto *CJ = getPrevDependentAction(BJ->getInputs(), CompileJobOffloadActions,
3364 /*CanBeCollapsed=*/false);
3365 if (!AJ || !BJ || !CJ)
3366 return nullptr;
3367
3368 assert(isa<CompileJobAction>(CJ) &&
3369 "Expecting compile job preceding backend job.");
3370
3371 // Get compiler tool.
3372 const Tool *T = TC.SelectTool(*CJ);
3373 if (!T)
3374 return nullptr;
3375
3376 if (!T->hasIntegratedAssembler())
3377 return nullptr;
3378
3379 Inputs = &BJ->getInputs();
3380 AppendCollapsedOffloadAction(CollapsedOffloadAction, ActionInfo,
3381 /*NumElements=*/2);
3382 return T;
3383 }
3384 const Tool *combineBackendCompile(ArrayRef<JobActionInfo> ActionInfo,
3385 const ActionList *&Inputs,
3386 ActionList &CollapsedOffloadAction) {
Teresa Johnson9e4321c2018-04-17 16:39:25 +00003387 if (ActionInfo.size() < 2)
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00003388 return nullptr;
3389 auto *BJ = dyn_cast<BackendJobAction>(ActionInfo[0].JA);
3390 auto *CJ = dyn_cast<CompileJobAction>(ActionInfo[1].JA);
3391 if (!BJ || !CJ)
3392 return nullptr;
3393
Teresa Johnson9e4321c2018-04-17 16:39:25 +00003394 // Check if the initial input (to the compile job or its predessor if one
3395 // exists) is LLVM bitcode. In that case, no preprocessor step is required
3396 // and we can still collapse the compile and backend jobs when we have
3397 // -save-temps. I.e. there is no need for a separate compile job just to
3398 // emit unoptimized bitcode.
3399 bool InputIsBitcode = true;
3400 for (size_t i = 1; i < ActionInfo.size(); i++)
3401 if (ActionInfo[i].JA->getType() != types::TY_LLVM_BC &&
3402 ActionInfo[i].JA->getType() != types::TY_LTO_BC) {
3403 InputIsBitcode = false;
3404 break;
3405 }
3406 if (!InputIsBitcode && !canCollapsePreprocessorAction())
3407 return nullptr;
3408
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00003409 // Get compiler tool.
3410 const Tool *T = TC.SelectTool(*CJ);
3411 if (!T)
3412 return nullptr;
3413
Teresa Johnson9e4321c2018-04-17 16:39:25 +00003414 if (T->canEmitIR() && ((SaveTemps && !InputIsBitcode) || EmbedBitcode))
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00003415 return nullptr;
3416
3417 Inputs = &CJ->getInputs();
3418 AppendCollapsedOffloadAction(CollapsedOffloadAction, ActionInfo,
3419 /*NumElements=*/2);
3420 return T;
3421 }
3422
3423 /// Updates the inputs if the obtained tool supports combining with
3424 /// preprocessor action, and the current input is indeed a preprocessor
3425 /// action. If combining results in the collapse of offloading actions, those
3426 /// are appended to \a CollapsedOffloadAction.
3427 void combineWithPreprocessor(const Tool *T, const ActionList *&Inputs,
3428 ActionList &CollapsedOffloadAction) {
3429 if (!T || !canCollapsePreprocessorAction() || !T->hasIntegratedCPP())
3430 return;
3431
3432 // Attempt to get a preprocessor action dependence.
3433 ActionList PreprocessJobOffloadActions;
3434 auto *PJ = getPrevDependentAction(*Inputs, PreprocessJobOffloadActions);
3435 if (!PJ || !isa<PreprocessJobAction>(PJ))
3436 return;
3437
3438 // This is legal to combine. Append any offload action we found and set the
3439 // current inputs to preprocessor inputs.
3440 CollapsedOffloadAction.append(PreprocessJobOffloadActions.begin(),
3441 PreprocessJobOffloadActions.end());
3442 Inputs = &PJ->getInputs();
3443 }
3444
3445public:
3446 ToolSelector(const JobAction *BaseAction, const ToolChain &TC,
3447 const Compilation &C, bool SaveTemps, bool EmbedBitcode)
3448 : TC(TC), C(C), BaseAction(BaseAction), SaveTemps(SaveTemps),
3449 EmbedBitcode(EmbedBitcode) {
3450 assert(BaseAction && "Invalid base action.");
3451 IsHostSelector = BaseAction->getOffloadingDeviceKind() == Action::OFK_None;
3452 }
3453
3454 /// Check if a chain of actions can be combined and return the tool that can
3455 /// handle the combination of actions. The pointer to the current inputs \a
3456 /// Inputs and the list of offload actions \a CollapsedOffloadActions
3457 /// connected to collapsed actions are updated accordingly. The latter enables
3458 /// the caller of the selector to process them afterwards instead of just
3459 /// dropping them. If no suitable tool is found, null will be returned.
3460 const Tool *getTool(const ActionList *&Inputs,
3461 ActionList &CollapsedOffloadAction) {
3462 //
3463 // Get the largest chain of actions that we could combine.
3464 //
3465
3466 SmallVector<JobActionInfo, 5> ActionChain(1);
3467 ActionChain.back().JA = BaseAction;
3468 while (ActionChain.back().JA) {
3469 const Action *CurAction = ActionChain.back().JA;
3470
3471 // Grow the chain by one element.
3472 ActionChain.resize(ActionChain.size() + 1);
3473 JobActionInfo &AI = ActionChain.back();
3474
3475 // Attempt to fill it with the
3476 AI.JA =
3477 getPrevDependentAction(CurAction->getInputs(), AI.SavedOffloadAction);
Daniel Dunbarc4343942010-02-03 03:07:56 +00003478 }
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00003479
3480 // Pop the last action info as it could not be filled.
3481 ActionChain.pop_back();
3482
3483 //
3484 // Attempt to combine actions. If all combining attempts failed, just return
3485 // the tool of the provided action. At the end we attempt to combine the
3486 // action with any preprocessor action it may depend on.
3487 //
3488
3489 const Tool *T = combineAssembleBackendCompile(ActionChain, Inputs,
3490 CollapsedOffloadAction);
3491 if (!T)
3492 T = combineAssembleBackend(ActionChain, Inputs, CollapsedOffloadAction);
3493 if (!T)
3494 T = combineBackendCompile(ActionChain, Inputs, CollapsedOffloadAction);
3495 if (!T) {
3496 Inputs = &BaseAction->getInputs();
3497 T = TC.SelectTool(*BaseAction);
3498 }
3499
3500 combineWithPreprocessor(T, Inputs, CollapsedOffloadAction);
3501 return T;
Daniel Dunbarc4343942010-02-03 03:07:56 +00003502 }
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00003503};
Daniel Dunbarc4343942010-02-03 03:07:56 +00003504}
3505
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003506/// Return a string that uniquely identifies the result of a job. The bound arch
3507/// is not necessarily represented in the toolchain's triple -- for example,
3508/// armv7 and armv7s both map to the same triple -- so we need both in our map.
3509/// Also, we need to add the offloading device kind, as the same tool chain can
3510/// be used for host and device for some programming models, e.g. OpenMP.
3511static std::string GetTriplePlusArchString(const ToolChain *TC,
3512 StringRef BoundArch,
3513 Action::OffloadKind OffloadKind) {
Justin Lebar55c83322016-01-16 03:30:08 +00003514 std::string TriplePlusArch = TC->getTriple().normalize();
Mehdi Aminic50b1a22016-10-07 21:27:26 +00003515 if (!BoundArch.empty()) {
Justin Lebar55c83322016-01-16 03:30:08 +00003516 TriplePlusArch += "-";
3517 TriplePlusArch += BoundArch;
3518 }
Samuel Antao59efaed2016-10-27 17:31:22 +00003519 TriplePlusArch += "-";
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003520 TriplePlusArch += Action::GetOffloadKindName(OffloadKind);
3521 return TriplePlusArch;
3522}
3523
3524InputInfo Driver::BuildJobsForAction(
3525 Compilation &C, const Action *A, const ToolChain *TC, StringRef BoundArch,
3526 bool AtTopLevel, bool MultipleArchs, const char *LinkingOutput,
3527 std::map<std::pair<const Action *, std::string>, InputInfo> &CachedResults,
3528 Action::OffloadKind TargetDeviceOffloadKind) const {
3529 std::pair<const Action *, std::string> ActionTC = {
3530 A, GetTriplePlusArchString(TC, BoundArch, TargetDeviceOffloadKind)};
Justin Lebarb44f6fe2016-01-14 21:41:21 +00003531 auto CachedResult = CachedResults.find(ActionTC);
3532 if (CachedResult != CachedResults.end()) {
3533 return CachedResult->second;
3534 }
Samuel Antaod06239d2016-07-15 23:13:27 +00003535 InputInfo Result = BuildJobsForActionNoCache(
3536 C, A, TC, BoundArch, AtTopLevel, MultipleArchs, LinkingOutput,
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003537 CachedResults, TargetDeviceOffloadKind);
Justin Lebarb44f6fe2016-01-14 21:41:21 +00003538 CachedResults[ActionTC] = Result;
3539 return Result;
3540}
3541
3542InputInfo Driver::BuildJobsForActionNoCache(
Mehdi Aminic50b1a22016-10-07 21:27:26 +00003543 Compilation &C, const Action *A, const ToolChain *TC, StringRef BoundArch,
Justin Lebarb44f6fe2016-01-14 21:41:21 +00003544 bool AtTopLevel, bool MultipleArchs, const char *LinkingOutput,
Samuel Antaod06239d2016-07-15 23:13:27 +00003545 std::map<std::pair<const Action *, std::string>, InputInfo> &CachedResults,
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003546 Action::OffloadKind TargetDeviceOffloadKind) const {
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00003547 llvm::PrettyStackTraceString CrashInfo("Building compilation jobs");
Daniel Dunbarc4acf9d2009-03-18 23:18:19 +00003548
Samuel Antaod06239d2016-07-15 23:13:27 +00003549 InputInfoList OffloadDependencesInputInfo;
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003550 bool BuildingForOffloadDevice = TargetDeviceOffloadKind != Action::OFK_None;
Samuel Antaod06239d2016-07-15 23:13:27 +00003551 if (const OffloadAction *OA = dyn_cast<OffloadAction>(A)) {
Alex Lorenz4003a982017-08-08 11:22:21 +00003552 // The 'Darwin' toolchain is initialized only when its arguments are
3553 // computed. Get the default arguments for OFK_None to ensure that
3554 // initialization is performed before processing the offload action.
3555 // FIXME: Remove when darwin's toolchain is initialized during construction.
3556 C.getArgsForToolChain(TC, BoundArch, Action::OFK_None);
3557
Samuel Antaod06239d2016-07-15 23:13:27 +00003558 // The offload action is expected to be used in four different situations.
3559 //
3560 // a) Set a toolchain/architecture/kind for a host action:
3561 // Host Action 1 -> OffloadAction -> Host Action 2
3562 //
3563 // b) Set a toolchain/architecture/kind for a device action;
3564 // Device Action 1 -> OffloadAction -> Device Action 2
3565 //
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00003566 // c) Specify a device dependence to a host action;
Samuel Antaod06239d2016-07-15 23:13:27 +00003567 // Device Action 1 _
3568 // \
3569 // Host Action 1 ---> OffloadAction -> Host Action 2
3570 //
3571 // d) Specify a host dependence to a device action.
3572 // Host Action 1 _
3573 // \
3574 // Device Action 1 ---> OffloadAction -> Device Action 2
3575 //
3576 // For a) and b), we just return the job generated for the dependence. For
3577 // c) and d) we override the current action with the host/device dependence
3578 // if the current toolchain is host/device and set the offload dependences
3579 // info with the jobs obtained from the device/host dependence(s).
3580
3581 // If there is a single device option, just generate the job for it.
3582 if (OA->hasSingleDeviceDependence()) {
3583 InputInfo DevA;
3584 OA->doOnEachDeviceDependence([&](Action *DepA, const ToolChain *DepTC,
3585 const char *DepBoundArch) {
3586 DevA =
3587 BuildJobsForAction(C, DepA, DepTC, DepBoundArch, AtTopLevel,
3588 /*MultipleArchs*/ !!DepBoundArch, LinkingOutput,
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003589 CachedResults, DepA->getOffloadingDeviceKind());
Samuel Antaod06239d2016-07-15 23:13:27 +00003590 });
3591 return DevA;
Artem Belevich0ff05cd2015-07-13 23:27:56 +00003592 }
Samuel Antaod06239d2016-07-15 23:13:27 +00003593
3594 // If 'Action 2' is host, we generate jobs for the device dependences and
3595 // override the current action with the host dependence. Otherwise, we
3596 // generate the host dependences and override the action with the device
3597 // dependence. The dependences can't therefore be a top-level action.
3598 OA->doOnEachDependence(
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003599 /*IsHostDependence=*/BuildingForOffloadDevice,
Samuel Antaod06239d2016-07-15 23:13:27 +00003600 [&](Action *DepA, const ToolChain *DepTC, const char *DepBoundArch) {
3601 OffloadDependencesInputInfo.push_back(BuildJobsForAction(
3602 C, DepA, DepTC, DepBoundArch, /*AtTopLevel=*/false,
3603 /*MultipleArchs*/ !!DepBoundArch, LinkingOutput, CachedResults,
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003604 DepA->getOffloadingDeviceKind()));
Samuel Antaod06239d2016-07-15 23:13:27 +00003605 });
3606
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003607 A = BuildingForOffloadDevice
Samuel Antaod06239d2016-07-15 23:13:27 +00003608 ? OA->getSingleDeviceDependence(/*DoNotConsiderHostActions=*/true)
3609 : OA->getHostDependence();
Artem Belevich0ff05cd2015-07-13 23:27:56 +00003610 }
3611
Daniel Dunbare75d8342009-03-16 06:56:51 +00003612 if (const InputAction *IA = dyn_cast<InputAction>(A)) {
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00003613 // FIXME: It would be nice to not claim this here; maybe the old scheme of
3614 // just using Args was better?
Daniel Dunbar5cdf3e02009-03-19 07:29:38 +00003615 const Arg &Input = IA->getInputArg();
3616 Input.claim();
Daniel Dunbar35cbfeb2010-06-09 22:31:08 +00003617 if (Input.getOption().matches(options::OPT_INPUT)) {
Richard Smithbd55daf2012-11-01 04:30:05 +00003618 const char *Name = Input.getValue();
Justin Lebard98cea82016-01-11 23:15:21 +00003619 return InputInfo(A, Name, /* BaseInput = */ Name);
Douglas Katzman678d0cb2015-06-16 18:01:24 +00003620 }
Justin Lebard98cea82016-01-11 23:15:21 +00003621 return InputInfo(A, &Input, /* BaseInput = */ "");
Daniel Dunbare75d8342009-03-16 06:56:51 +00003622 }
3623
3624 if (const BindArchAction *BAA = dyn_cast<BindArchAction>(A)) {
Chad Rosiera78a6eb2012-04-27 16:50:38 +00003625 const ToolChain *TC;
Mehdi Aminic50b1a22016-10-07 21:27:26 +00003626 StringRef ArchName = BAA->getArchName();
Daniel Dunbar1ef3f2a2009-09-08 23:37:19 +00003627
Mehdi Aminic50b1a22016-10-07 21:27:26 +00003628 if (!ArchName.empty())
Andrey Turetskiy6a8b91d2016-04-21 10:16:48 +00003629 TC = &getToolChain(C.getArgs(),
3630 computeTargetTriple(*this, DefaultTargetTriple,
3631 C.getArgs(), ArchName));
Chad Rosiera78a6eb2012-04-27 16:50:38 +00003632 else
3633 TC = &C.getDefaultToolChain();
Daniel Dunbar1ef3f2a2009-09-08 23:37:19 +00003634
Nico Weber5a459f82016-02-23 19:30:43 +00003635 return BuildJobsForAction(C, *BAA->input_begin(), TC, ArchName, AtTopLevel,
Samuel Antaod06239d2016-07-15 23:13:27 +00003636 MultipleArchs, LinkingOutput, CachedResults,
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003637 TargetDeviceOffloadKind);
Daniel Dunbare75d8342009-03-16 06:56:51 +00003638 }
3639
Artem Belevich0ff05cd2015-07-13 23:27:56 +00003640
Daniel Dunbare75d8342009-03-16 06:56:51 +00003641 const ActionList *Inputs = &A->getInputs();
Daniel Dunbarc4343942010-02-03 03:07:56 +00003642
3643 const JobAction *JA = cast<JobAction>(A);
Samuel Antaod06239d2016-07-15 23:13:27 +00003644 ActionList CollapsedOffloadActions;
3645
Mehdi Amini6683e222017-01-24 18:12:25 +00003646 ToolSelector TS(JA, *TC, C, isSaveTempsEnabled(),
3647 embedBitcodeInObject() && !isUsingLTO());
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00003648 const Tool *T = TS.getTool(Inputs, CollapsedOffloadActions);
3649
Rafael Espindola79764462013-03-24 15:06:53 +00003650 if (!T)
Justin Lebar9eaa4892016-01-11 23:09:32 +00003651 return InputInfo();
Daniel Dunbare75d8342009-03-16 06:56:51 +00003652
Samuel Antaod06239d2016-07-15 23:13:27 +00003653 // If we've collapsed action list that contained OffloadAction we
3654 // need to build jobs for host/device-side inputs it may have held.
3655 for (const auto *OA : CollapsedOffloadActions)
3656 cast<OffloadAction>(OA)->doOnEachDependence(
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003657 /*IsHostDependence=*/BuildingForOffloadDevice,
Samuel Antaod06239d2016-07-15 23:13:27 +00003658 [&](Action *DepA, const ToolChain *DepTC, const char *DepBoundArch) {
3659 OffloadDependencesInputInfo.push_back(BuildJobsForAction(
Artem Belevichbee2f412016-08-22 18:50:34 +00003660 C, DepA, DepTC, DepBoundArch, /* AtTopLevel */ false,
Samuel Antaod06239d2016-07-15 23:13:27 +00003661 /*MultipleArchs=*/!!DepBoundArch, LinkingOutput, CachedResults,
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003662 DepA->getOffloadingDeviceKind()));
Samuel Antaod06239d2016-07-15 23:13:27 +00003663 });
Artem Belevichf8144ab2015-08-27 18:10:41 +00003664
Daniel Dunbare75d8342009-03-16 06:56:51 +00003665 // Only use pipes when there is exactly one input.
Daniel Dunbar1a093d22009-03-18 06:00:36 +00003666 InputInfoList InputInfos;
Saleem Abdulrasoolda3f4e52014-12-29 21:02:47 +00003667 for (const Action *Input : *Inputs) {
Eric Christopher14668dd2013-02-18 00:38:25 +00003668 // Treat dsymutil and verify sub-jobs as being at the top-level too, they
3669 // shouldn't get temporary output names.
Daniel Dunbar6beaf512010-06-04 18:28:41 +00003670 // FIXME: Clean this up.
Justin Lebar9eaa4892016-01-11 23:09:32 +00003671 bool SubJobAtTopLevel =
3672 AtTopLevel && (isa<DsymutilJobAction>(A) || isa<VerifyJobAction>(A));
Samuel Antaod06239d2016-07-15 23:13:27 +00003673 InputInfos.push_back(BuildJobsForAction(
3674 C, Input, TC, BoundArch, SubJobAtTopLevel, MultipleArchs, LinkingOutput,
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003675 CachedResults, A->getOffloadingDeviceKind()));
Daniel Dunbare75d8342009-03-16 06:56:51 +00003676 }
3677
Daniel Dunbare75d8342009-03-16 06:56:51 +00003678 // Always use the first input as the base input.
3679 const char *BaseInput = InputInfos[0].getBaseInput();
Daniel Dunbar7a178a42009-03-17 17:53:55 +00003680
Daniel Dunbar6beaf512010-06-04 18:28:41 +00003681 // ... except dsymutil actions, which use their actual input as the base
3682 // input.
3683 if (JA->getType() == types::TY_dSYM)
3684 BaseInput = InputInfos[0].getFilename();
3685
Samuel Antaod06239d2016-07-15 23:13:27 +00003686 // Append outputs of offload device jobs to the input list
3687 if (!OffloadDependencesInputInfo.empty())
3688 InputInfos.append(OffloadDependencesInputInfo.begin(),
3689 OffloadDependencesInputInfo.end());
Artem Belevich0ff05cd2015-07-13 23:27:56 +00003690
Vedant Kumar18286cf2016-07-27 23:02:20 +00003691 // Set the effective triple of the toolchain for the duration of this job.
3692 llvm::Triple EffectiveTriple;
3693 const ToolChain &ToolTC = T->getToolChain();
Samuel Antao31fef982016-10-27 17:39:44 +00003694 const ArgList &Args =
3695 C.getArgsForToolChain(TC, BoundArch, A->getOffloadingDeviceKind());
Vedant Kumar18286cf2016-07-27 23:02:20 +00003696 if (InputInfos.size() != 1) {
3697 EffectiveTriple = llvm::Triple(ToolTC.ComputeEffectiveClangTriple(Args));
3698 } else {
3699 // Pass along the input type if it can be unambiguously determined.
3700 EffectiveTriple = llvm::Triple(
3701 ToolTC.ComputeEffectiveClangTriple(Args, InputInfos[0].getType()));
3702 }
3703 RegisterEffectiveTriple TripleRAII(ToolTC, EffectiveTriple);
3704
Daniel Dunbard00272f2010-08-02 02:38:15 +00003705 // Determine the place to write output to, if any.
Justin Lebar9eaa4892016-01-11 23:09:32 +00003706 InputInfo Result;
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003707 InputInfoList UnbundlingResults;
3708 if (auto *UA = dyn_cast<OffloadUnbundlingJobAction>(JA)) {
3709 // If we have an unbundling job, we need to create results for all the
3710 // outputs. We also update the results cache so that other actions using
3711 // this unbundling action can get the right results.
3712 for (auto &UI : UA->getDependentActionsInfo()) {
3713 assert(UI.DependentOffloadKind != Action::OFK_None &&
3714 "Unbundling with no offloading??");
3715
3716 // Unbundling actions are never at the top level. When we generate the
3717 // offloading prefix, we also do that for the host file because the
3718 // unbundling action does not change the type of the output which can
3719 // cause a overwrite.
3720 std::string OffloadingPrefix = Action::GetOffloadingFileNamePrefix(
3721 UI.DependentOffloadKind,
3722 UI.DependentToolChain->getTriple().normalize(),
3723 /*CreatePrefixForHost=*/true);
3724 auto CurI = InputInfo(
3725 UA, GetNamedOutputPath(C, *UA, BaseInput, UI.DependentBoundArch,
3726 /*AtTopLevel=*/false, MultipleArchs,
3727 OffloadingPrefix),
3728 BaseInput);
3729 // Save the unbundling result.
3730 UnbundlingResults.push_back(CurI);
3731
3732 // Get the unique string identifier for this dependence and cache the
3733 // result.
3734 CachedResults[{A, GetTriplePlusArchString(
Gheorghe-Teodor Bercea52898432017-08-09 01:02:19 +00003735 UI.DependentToolChain, BoundArch,
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003736 UI.DependentOffloadKind)}] = CurI;
3737 }
3738
3739 // Now that we have all the results generated, select the one that should be
3740 // returned for the current depending action.
3741 std::pair<const Action *, std::string> ActionTC = {
3742 A, GetTriplePlusArchString(TC, BoundArch, TargetDeviceOffloadKind)};
3743 assert(CachedResults.find(ActionTC) != CachedResults.end() &&
3744 "Result does not exist??");
3745 Result = CachedResults[ActionTC];
3746 } else if (JA->getType() == types::TY_Nothing)
Justin Lebard98cea82016-01-11 23:15:21 +00003747 Result = InputInfo(A, BaseInput);
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003748 else {
3749 // We only have to generate a prefix for the host if this is not a top-level
3750 // action.
3751 std::string OffloadingPrefix = Action::GetOffloadingFileNamePrefix(
3752 A->getOffloadingDeviceKind(), TC->getTriple().normalize(),
3753 /*CreatePrefixForHost=*/!!A->getOffloadingHostActiveKinds() &&
3754 !AtTopLevel);
Justin Lebard98cea82016-01-11 23:15:21 +00003755 Result = InputInfo(A, GetNamedOutputPath(C, *JA, BaseInput, BoundArch,
Samuel Antaod06239d2016-07-15 23:13:27 +00003756 AtTopLevel, MultipleArchs,
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003757 OffloadingPrefix),
Justin Lebard98cea82016-01-11 23:15:21 +00003758 BaseInput);
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003759 }
Daniel Dunbar7a178a42009-03-17 17:53:55 +00003760
Chad Rosierbe10f982011-08-02 17:58:04 +00003761 if (CCCPrintBindings && !CCGenDiagnostics) {
Rafael Espindola79764462013-03-24 15:06:53 +00003762 llvm::errs() << "# \"" << T->getToolChain().getTripleString() << '"'
3763 << " - \"" << T->getName() << "\", inputs: [";
Daniel Dunbarb39cc522009-03-17 22:47:06 +00003764 for (unsigned i = 0, e = InputInfos.size(); i != e; ++i) {
3765 llvm::errs() << InputInfos[i].getAsString();
3766 if (i + 1 != e)
3767 llvm::errs() << ", ";
3768 }
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003769 if (UnbundlingResults.empty())
3770 llvm::errs() << "], output: " << Result.getAsString() << "\n";
3771 else {
3772 llvm::errs() << "], outputs: [";
3773 for (unsigned i = 0, e = UnbundlingResults.size(); i != e; ++i) {
3774 llvm::errs() << UnbundlingResults[i].getAsString();
3775 if (i + 1 != e)
3776 llvm::errs() << ", ";
3777 }
3778 llvm::errs() << "] \n";
3779 }
Daniel Dunbarb39cc522009-03-17 22:47:06 +00003780 } else {
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003781 if (UnbundlingResults.empty())
3782 T->ConstructJob(
3783 C, *JA, Result, InputInfos,
3784 C.getArgsForToolChain(TC, BoundArch, JA->getOffloadingDeviceKind()),
3785 LinkingOutput);
3786 else
Samuel Antao7108bf32016-11-03 15:41:50 +00003787 T->ConstructJobMultipleOutputs(
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003788 C, *JA, UnbundlingResults, InputInfos,
3789 C.getArgsForToolChain(TC, BoundArch, JA->getOffloadingDeviceKind()),
3790 LinkingOutput);
Daniel Dunbarb39cc522009-03-17 22:47:06 +00003791 }
Justin Lebar9eaa4892016-01-11 23:09:32 +00003792 return Result;
Daniel Dunbare75d8342009-03-16 06:56:51 +00003793}
3794
Hans Wennborga7707222015-01-09 17:38:53 +00003795const char *Driver::getDefaultImageName() const {
3796 llvm::Triple Target(llvm::Triple::normalize(DefaultTargetTriple));
3797 return Target.isOSWindows() ? "a.exe" : "a.out";
3798}
3799
Hans Wennborg2c21f742013-10-17 16:16:23 +00003800/// \brief Create output filename based on ArgValue, which could either be a
3801/// full filename, filename without extension, or a directory. If ArgValue
3802/// does not provide a filename, then use BaseName, and use the extension
3803/// suitable for FileType.
Hans Wennborg207fcf02013-08-12 21:56:42 +00003804static const char *MakeCLOutputFilename(const ArgList &Args, StringRef ArgValue,
Douglas Katzmana67e50c2015-06-26 15:47:46 +00003805 StringRef BaseName,
3806 types::ID FileType) {
Hans Wennborg207fcf02013-08-12 21:56:42 +00003807 SmallString<128> Filename = ArgValue;
Justin Bogner5aaf2e72014-06-26 20:59:36 +00003808
Hans Wennborgf1a74252013-09-10 20:18:04 +00003809 if (ArgValue.empty()) {
3810 // If the argument is empty, output to BaseName in the current dir.
3811 Filename = BaseName;
3812 } else if (llvm::sys::path::is_separator(Filename.back())) {
Hans Wennborg207fcf02013-08-12 21:56:42 +00003813 // If the argument is a directory, output to BaseName in that dir.
3814 llvm::sys::path::append(Filename, BaseName);
3815 }
3816
3817 if (!llvm::sys::path::has_extension(ArgValue)) {
3818 // If the argument didn't provide an extension, then set it.
3819 const char *Extension = types::getTypeTempSuffix(FileType, true);
Hans Wennborgf1a74252013-09-10 20:18:04 +00003820
3821 if (FileType == types::TY_Image &&
3822 Args.hasArg(options::OPT__SLASH_LD, options::OPT__SLASH_LDd)) {
3823 // The output file is a dll.
3824 Extension = "dll";
3825 }
3826
Hans Wennborg207fcf02013-08-12 21:56:42 +00003827 llvm::sys::path::replace_extension(Filename, Extension);
3828 }
3829
3830 return Args.MakeArgString(Filename.c_str());
3831}
3832
Douglas Katzmana67e50c2015-06-26 15:47:46 +00003833const char *Driver::GetNamedOutputPath(Compilation &C, const JobAction &JA,
Daniel Dunbar7a178a42009-03-17 17:53:55 +00003834 const char *BaseInput,
Mehdi Aminic50b1a22016-10-07 21:27:26 +00003835 StringRef BoundArch, bool AtTopLevel,
Samuel Antaod06239d2016-07-15 23:13:27 +00003836 bool MultipleArchs,
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003837 StringRef OffloadingPrefix) const {
Daniel Dunbar2608c542009-03-18 01:38:48 +00003838 llvm::PrettyStackTraceString CrashInfo("Computing output path");
Daniel Dunbar7a178a42009-03-17 17:53:55 +00003839 // Output to a user requested destination?
Douglas Katzmana67e50c2015-06-26 15:47:46 +00003840 if (AtTopLevel && !isa<DsymutilJobAction>(JA) && !isa<VerifyJobAction>(JA)) {
Daniel Dunbar7a178a42009-03-17 17:53:55 +00003841 if (Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o))
Chad Rosier633dcdc2013-01-24 19:14:47 +00003842 return C.addResultFile(FinalOutput->getValue(), &JA);
Daniel Dunbar7a178a42009-03-17 17:53:55 +00003843 }
3844
Hans Wennborge0053472013-12-20 18:40:46 +00003845 // For /P, preprocess to file named after BaseInput.
3846 if (C.getArgs().hasArg(options::OPT__SLASH_P)) {
3847 assert(AtTopLevel && isa<PreprocessJobAction>(JA));
3848 StringRef BaseName = llvm::sys::path::filename(BaseInput);
Hans Wennborg04c764f2014-06-17 00:19:12 +00003849 StringRef NameArg;
Greg Bedwell065f70a2015-06-09 10:24:06 +00003850 if (Arg *A = C.getArgs().getLastArg(options::OPT__SLASH_Fi))
Hans Wennborg04c764f2014-06-17 00:19:12 +00003851 NameArg = A->getValue();
Douglas Katzmana67e50c2015-06-26 15:47:46 +00003852 return C.addResultFile(
3853 MakeCLOutputFilename(C.getArgs(), NameArg, BaseName, types::TY_PP_C),
3854 &JA);
Hans Wennborge0053472013-12-20 18:40:46 +00003855 }
3856
Nick Lewycky6e1ce292010-09-24 00:46:53 +00003857 // Default to writing to stdout?
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +00003858 if (AtTopLevel && !CCGenDiagnostics &&
3859 (isa<PreprocessJobAction>(JA) || JA.getType() == types::TY_ModuleFile))
Nick Lewycky6e1ce292010-09-24 00:46:53 +00003860 return "-";
3861
Hans Wennborg2c21f742013-10-17 16:16:23 +00003862 // Is this the assembly listing for /FA?
3863 if (JA.getType() == types::TY_PP_Asm &&
3864 (C.getArgs().hasArg(options::OPT__SLASH_FA) ||
3865 C.getArgs().hasArg(options::OPT__SLASH_Fa))) {
3866 // Use /Fa and the input filename to determine the asm file name.
3867 StringRef BaseName = llvm::sys::path::filename(BaseInput);
3868 StringRef FaValue = C.getArgs().getLastArgValue(options::OPT__SLASH_Fa);
Douglas Katzmana67e50c2015-06-26 15:47:46 +00003869 return C.addResultFile(
3870 MakeCLOutputFilename(C.getArgs(), FaValue, BaseName, JA.getType()),
3871 &JA);
Hans Wennborg2c21f742013-10-17 16:16:23 +00003872 }
3873
Daniel Dunbar7a178a42009-03-17 17:53:55 +00003874 // Output to a temporary file?
Reid Kleckner68eb60b2015-02-02 22:41:48 +00003875 if ((!AtTopLevel && !isSaveTempsEnabled() &&
Douglas Katzmana67e50c2015-06-26 15:47:46 +00003876 !C.getArgs().hasArg(options::OPT__SLASH_Fo)) ||
Chad Rosierbe10f982011-08-02 17:58:04 +00003877 CCGenDiagnostics) {
Chad Rosier97c37372011-08-26 22:27:02 +00003878 StringRef Name = llvm::sys::path::filename(BaseInput);
3879 std::pair<StringRef, StringRef> Split = Name.split('.');
Douglas Katzmana67e50c2015-06-26 15:47:46 +00003880 std::string TmpName = GetTemporaryPath(
3881 Split.first, types::getTypeTempSuffix(JA.getType(), IsCLMode()));
Malcolm Parsonsf76f6502016-11-02 10:39:27 +00003882 return C.addTempFile(C.getArgs().MakeArgString(TmpName));
Daniel Dunbar7a178a42009-03-17 17:53:55 +00003883 }
3884
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00003885 SmallString<128> BasePath(BaseInput);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003886 StringRef BaseName;
Daniel Dunbar67fea712011-03-25 18:16:51 +00003887
3888 // Dsymutil actions should use the full path.
Eric Christopher551ef452011-08-23 17:56:55 +00003889 if (isa<DsymutilJobAction>(JA) || isa<VerifyJobAction>(JA))
Daniel Dunbar67fea712011-03-25 18:16:51 +00003890 BaseName = BasePath;
3891 else
3892 BaseName = llvm::sys::path::filename(BasePath);
Daniel Dunbar7a178a42009-03-17 17:53:55 +00003893
3894 // Determine what the derived output name should be.
3895 const char *NamedOutput;
Hans Wennborg2b89a262013-08-06 22:11:28 +00003896
Hans Wennborg625fba82016-10-04 21:01:04 +00003897 if ((JA.getType() == types::TY_Object || JA.getType() == types::TY_LTO_BC) &&
Ehsan Akhgari81f36b72014-09-11 18:16:21 +00003898 C.getArgs().hasArg(options::OPT__SLASH_Fo, options::OPT__SLASH_o)) {
3899 // The /Fo or /o flag decides the object filename.
Douglas Katzmana67e50c2015-06-26 15:47:46 +00003900 StringRef Val =
3901 C.getArgs()
3902 .getLastArg(options::OPT__SLASH_Fo, options::OPT__SLASH_o)
3903 ->getValue();
3904 NamedOutput =
3905 MakeCLOutputFilename(C.getArgs(), Val, BaseName, types::TY_Object);
Hans Wennborg207fcf02013-08-12 21:56:42 +00003906 } else if (JA.getType() == types::TY_Image &&
Douglas Katzmana67e50c2015-06-26 15:47:46 +00003907 C.getArgs().hasArg(options::OPT__SLASH_Fe,
3908 options::OPT__SLASH_o)) {
Ehsan Akhgari81f36b72014-09-11 18:16:21 +00003909 // The /Fe or /o flag names the linked file.
Douglas Katzmana67e50c2015-06-26 15:47:46 +00003910 StringRef Val =
3911 C.getArgs()
3912 .getLastArg(options::OPT__SLASH_Fe, options::OPT__SLASH_o)
3913 ->getValue();
3914 NamedOutput =
3915 MakeCLOutputFilename(C.getArgs(), Val, BaseName, types::TY_Image);
Hans Wennborgf1a74252013-09-10 20:18:04 +00003916 } else if (JA.getType() == types::TY_Image) {
Hans Wennborg207fcf02013-08-12 21:56:42 +00003917 if (IsCLMode()) {
3918 // clang-cl uses BaseName for the executable name.
Douglas Katzmana67e50c2015-06-26 15:47:46 +00003919 NamedOutput =
3920 MakeCLOutputFilename(C.getArgs(), "", BaseName, types::TY_Image);
Samuel Antao59efaed2016-10-27 17:31:22 +00003921 } else {
Hans Wennborga7707222015-01-09 17:38:53 +00003922 SmallString<128> Output(getDefaultImageName());
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003923 Output += OffloadingPrefix;
Samuel Antao59efaed2016-10-27 17:31:22 +00003924 if (MultipleArchs && !BoundArch.empty()) {
3925 Output += "-";
3926 Output.append(BoundArch);
3927 }
Chad Rosier35767232013-04-30 22:01:21 +00003928 NamedOutput = C.getArgs().MakeArgString(Output.c_str());
Nico Weber2ca4be92016-03-01 23:16:44 +00003929 }
3930 } else if (JA.getType() == types::TY_PCH && IsCLMode()) {
Malcolm Parsonsf76f6502016-11-02 10:39:27 +00003931 NamedOutput = C.getArgs().MakeArgString(GetClPchPath(C, BaseName));
Daniel Dunbar7a178a42009-03-17 17:53:55 +00003932 } else {
Hans Wennborg0a096a02013-09-05 17:05:56 +00003933 const char *Suffix = types::getTypeTempSuffix(JA.getType(), IsCLMode());
Daniel Dunbar7a178a42009-03-17 17:53:55 +00003934 assert(Suffix && "All types used for output should have a suffix.");
3935
3936 std::string::size_type End = std::string::npos;
3937 if (!types::appendSuffixForType(JA.getType()))
3938 End = BaseName.rfind('.');
Chad Rosier35767232013-04-30 22:01:21 +00003939 SmallString<128> Suffixed(BaseName.substr(0, End));
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003940 Suffixed += OffloadingPrefix;
Mehdi Aminic50b1a22016-10-07 21:27:26 +00003941 if (MultipleArchs && !BoundArch.empty()) {
Chad Rosier35767232013-04-30 22:01:21 +00003942 Suffixed += "-";
3943 Suffixed.append(BoundArch);
3944 }
Bob Wilson23a55f12014-12-21 07:00:00 +00003945 // When using both -save-temps and -emit-llvm, use a ".tmp.bc" suffix for
3946 // the unoptimized bitcode so that it does not get overwritten by the ".bc"
3947 // optimized bitcode output.
3948 if (!AtTopLevel && C.getArgs().hasArg(options::OPT_emit_llvm) &&
3949 JA.getType() == types::TY_LLVM_BC)
3950 Suffixed += ".tmp";
Daniel Dunbar7a178a42009-03-17 17:53:55 +00003951 Suffixed += '.';
3952 Suffixed += Suffix;
3953 NamedOutput = C.getArgs().MakeArgString(Suffixed.c_str());
3954 }
3955
Reid Kleckner68eb60b2015-02-02 22:41:48 +00003956 // Prepend object file path if -save-temps=obj
3957 if (!AtTopLevel && isSaveTempsObj() && C.getArgs().hasArg(options::OPT_o) &&
3958 JA.getType() != types::TY_PCH) {
3959 Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o);
3960 SmallString<128> TempPath(FinalOutput->getValue());
3961 llvm::sys::path::remove_filename(TempPath);
3962 StringRef OutputFileName = llvm::sys::path::filename(NamedOutput);
3963 llvm::sys::path::append(TempPath, OutputFileName);
3964 NamedOutput = C.getArgs().MakeArgString(TempPath.c_str());
3965 }
3966
Chad Rosier62135492012-07-09 17:31:28 +00003967 // If we're saving temps and the temp file conflicts with the input file,
Chad Rosier5b58af02012-04-20 20:05:08 +00003968 // then avoid overwriting input file.
Reid Kleckner68eb60b2015-02-02 22:41:48 +00003969 if (!AtTopLevel && isSaveTempsEnabled() && NamedOutput == BaseName) {
Chad Rosier5b58af02012-04-20 20:05:08 +00003970 bool SameFile = false;
3971 SmallString<256> Result;
3972 llvm::sys::fs::current_path(Result);
3973 llvm::sys::path::append(Result, BaseName);
3974 llvm::sys::fs::equivalent(BaseInput, Result.c_str(), SameFile);
3975 // Must share the same path to conflict.
3976 if (SameFile) {
3977 StringRef Name = llvm::sys::path::filename(BaseInput);
3978 std::pair<StringRef, StringRef> Split = Name.split('.');
Douglas Katzmana67e50c2015-06-26 15:47:46 +00003979 std::string TmpName = GetTemporaryPath(
3980 Split.first, types::getTypeTempSuffix(JA.getType(), IsCLMode()));
Malcolm Parsonsf76f6502016-11-02 10:39:27 +00003981 return C.addTempFile(C.getArgs().MakeArgString(TmpName));
Chad Rosier5b58af02012-04-20 20:05:08 +00003982 }
Chad Rosierf8412cd2011-07-15 21:54:29 +00003983 }
3984
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00003985 // As an annoying special case, PCH generation doesn't strip the pathname.
Nico Weber8ab92192016-03-02 23:29:29 +00003986 if (JA.getType() == types::TY_PCH && !IsCLMode()) {
Michael J. Spencere1696752010-12-18 00:19:12 +00003987 llvm::sys::path::remove_filename(BasePath);
3988 if (BasePath.empty())
Daniel Dunbare6c83192009-03-18 09:58:30 +00003989 BasePath = NamedOutput;
3990 else
Michael J. Spencere1696752010-12-18 00:19:12 +00003991 llvm::sys::path::append(BasePath, NamedOutput);
Chad Rosier633dcdc2013-01-24 19:14:47 +00003992 return C.addResultFile(C.getArgs().MakeArgString(BasePath.c_str()), &JA);
Daniel Dunbar7a178a42009-03-17 17:53:55 +00003993 } else {
Chad Rosier633dcdc2013-01-24 19:14:47 +00003994 return C.addResultFile(NamedOutput, &JA);
Daniel Dunbar7a178a42009-03-17 17:53:55 +00003995 }
3996}
3997
Mehdi Amini12011172016-10-06 05:11:48 +00003998std::string Driver::GetFilePath(StringRef Name, const ToolChain &TC) const {
Chandler Carruth84559242010-03-22 01:52:07 +00003999 // Respect a limited subset of the '-Bprefix' functionality in GCC by
Logan Chiencd679fd2012-10-04 08:08:56 +00004000 // attempting to use this prefix when looking for file paths.
Douglas Katzman26eabf62015-06-24 15:10:30 +00004001 for (const std::string &Dir : PrefixDirs) {
Joerg Sonnenberger6165ab12011-03-21 13:51:29 +00004002 if (Dir.empty())
4003 continue;
Douglas Katzman26eabf62015-06-24 15:10:30 +00004004 SmallString<128> P(Dir[0] == '=' ? SysRoot + Dir.substr(1) : Dir);
Rafael Espindola609a6642013-06-24 18:33:43 +00004005 llvm::sys::path::append(P, Name);
4006 if (llvm::sys::fs::exists(Twine(P)))
Chandler Carruth84559242010-03-22 01:52:07 +00004007 return P.str();
4008 }
4009
Petr Hosek916a4672017-08-10 04:16:38 +00004010 SmallString<128> R(ResourceDir);
4011 llvm::sys::path::append(R, Name);
4012 if (llvm::sys::fs::exists(Twine(R)))
4013 return R.str();
4014
4015 SmallString<128> P(TC.getCompilerRTPath());
Rafael Espindola609a6642013-06-24 18:33:43 +00004016 llvm::sys::path::append(P, Name);
4017 if (llvm::sys::fs::exists(Twine(P)))
Peter Collingbournefa9771f2011-09-06 02:08:31 +00004018 return P.str();
4019
Douglas Katzman26eabf62015-06-24 15:10:30 +00004020 for (const std::string &Dir : TC.getFilePaths()) {
Joerg Sonnenberger6165ab12011-03-21 13:51:29 +00004021 if (Dir.empty())
4022 continue;
Douglas Katzman26eabf62015-06-24 15:10:30 +00004023 SmallString<128> P(Dir[0] == '=' ? SysRoot + Dir.substr(1) : Dir);
Rafael Espindola609a6642013-06-24 18:33:43 +00004024 llvm::sys::path::append(P, Name);
4025 if (llvm::sys::fs::exists(Twine(P)))
Daniel Dunbar1ce81532009-09-09 22:33:00 +00004026 return P.str();
Daniel Dunbar68b01a02009-03-18 20:26:19 +00004027 }
4028
Daniel Dunbar1ce81532009-09-09 22:33:00 +00004029 return Name;
Daniel Dunbar5e0f6af2009-03-13 00:51:18 +00004030}
4031
Douglas Katzmana67e50c2015-06-26 15:47:46 +00004032void Driver::generatePrefixedToolNames(
Mehdi Amini12011172016-10-06 05:11:48 +00004033 StringRef Tool, const ToolChain &TC,
Douglas Katzmana67e50c2015-06-26 15:47:46 +00004034 SmallVectorImpl<std::string> &Names) const {
Saleem Abdulrasoolf0ba6ce2014-10-25 23:33:21 +00004035 // FIXME: Needs a better variable than DefaultTargetTriple
Mehdi Amini12011172016-10-06 05:11:48 +00004036 Names.emplace_back((DefaultTargetTriple + "-" + Tool).str());
Benjamin Kramer3204b152015-05-29 19:42:19 +00004037 Names.emplace_back(Tool);
Vasileios Kalintirisc744e122015-11-12 15:26:54 +00004038
4039 // Allow the discovery of tools prefixed with LLVM's default target triple.
4040 std::string LLVMDefaultTargetTriple = llvm::sys::getDefaultTargetTriple();
4041 if (LLVMDefaultTargetTriple != DefaultTargetTriple)
Mehdi Amini12011172016-10-06 05:11:48 +00004042 Names.emplace_back((LLVMDefaultTargetTriple + "-" + Tool).str());
Saleem Abdulrasoolf0ba6ce2014-10-25 23:33:21 +00004043}
4044
Benjamin Kramer7111b912014-11-04 20:26:01 +00004045static bool ScanDirForExecutable(SmallString<128> &Dir,
4046 ArrayRef<std::string> Names) {
Saleem Abdulrasoolf0ba6ce2014-10-25 23:33:21 +00004047 for (const auto &Name : Names) {
4048 llvm::sys::path::append(Dir, Name);
4049 if (llvm::sys::fs::can_execute(Twine(Dir)))
4050 return true;
4051 llvm::sys::path::remove_filename(Dir);
4052 }
4053 return false;
4054}
4055
Mehdi Amini12011172016-10-06 05:11:48 +00004056std::string Driver::GetProgramPath(StringRef Name, const ToolChain &TC) const {
Saleem Abdulrasoolf0ba6ce2014-10-25 23:33:21 +00004057 SmallVector<std::string, 2> TargetSpecificExecutables;
4058 generatePrefixedToolNames(Name, TC, TargetSpecificExecutables);
4059
Chandler Carruth84559242010-03-22 01:52:07 +00004060 // Respect a limited subset of the '-Bprefix' functionality in GCC by
Logan Chiencd679fd2012-10-04 08:08:56 +00004061 // attempting to use this prefix when looking for program paths.
Saleem Abdulrasool23d99b12014-09-16 03:48:32 +00004062 for (const auto &PrefixDir : PrefixDirs) {
4063 if (llvm::sys::fs::is_directory(PrefixDir)) {
4064 SmallString<128> P(PrefixDir);
Saleem Abdulrasoolf0ba6ce2014-10-25 23:33:21 +00004065 if (ScanDirForExecutable(P, TargetSpecificExecutables))
Rafael Espindola8be5c052013-06-19 13:24:29 +00004066 return P.str();
Simon Atanasyana47ba292012-10-31 14:39:28 +00004067 } else {
Mehdi Amini12011172016-10-06 05:11:48 +00004068 SmallString<128> P((PrefixDir + Name).str());
Rafael Espindola609a6642013-06-24 18:33:43 +00004069 if (llvm::sys::fs::can_execute(Twine(P)))
Rafael Espindola8be5c052013-06-19 13:24:29 +00004070 return P.str();
Simon Atanasyan86bdab72012-10-31 12:01:53 +00004071 }
Chandler Carruth84559242010-03-22 01:52:07 +00004072 }
4073
Daniel Dunbar68b01a02009-03-18 20:26:19 +00004074 const ToolChain::path_list &List = TC.getProgramPaths();
Saleem Abdulrasool23d99b12014-09-16 03:48:32 +00004075 for (const auto &Path : List) {
4076 SmallString<128> P(Path);
Saleem Abdulrasoolf0ba6ce2014-10-25 23:33:21 +00004077 if (ScanDirForExecutable(P, TargetSpecificExecutables))
Rafael Espindola8be5c052013-06-19 13:24:29 +00004078 return P.str();
Daniel Dunbar68b01a02009-03-18 20:26:19 +00004079 }
4080
Daniel Dunbar76ce7412009-03-23 16:15:50 +00004081 // If all else failed, search the path.
Michael J. Spencerb011d482014-11-07 21:30:32 +00004082 for (const auto &TargetSpecificExecutable : TargetSpecificExecutables)
4083 if (llvm::ErrorOr<std::string> P =
4084 llvm::sys::findProgramByName(TargetSpecificExecutable))
Michael J. Spencer04162ea2014-11-04 01:30:55 +00004085 return *P;
Daniel Dunbar6f668772009-03-18 21:34:08 +00004086
Daniel Dunbar1ce81532009-09-09 22:33:00 +00004087 return Name;
Daniel Dunbar5e0f6af2009-03-13 00:51:18 +00004088}
4089
Mehdi Amini12011172016-10-06 05:11:48 +00004090std::string Driver::GetTemporaryPath(StringRef Prefix, StringRef Suffix) const {
Rafael Espindola37d229d2013-06-25 04:26:55 +00004091 SmallString<128> Path;
Rafael Espindolac0809172014-06-12 14:02:15 +00004092 std::error_code EC = llvm::sys::fs::createTemporaryFile(Prefix, Suffix, Path);
Rafael Espindola37d229d2013-06-25 04:26:55 +00004093 if (EC) {
4094 Diag(clang::diag::err_unable_to_make_temp) << EC.message();
Daniel Dunbare627c1c2009-03-18 19:34:39 +00004095 return "";
4096 }
4097
Rafael Espindola37d229d2013-06-25 04:26:55 +00004098 return Path.str();
Daniel Dunbare627c1c2009-03-18 19:34:39 +00004099}
4100
Nico Weber2ca4be92016-03-01 23:16:44 +00004101std::string Driver::GetClPchPath(Compilation &C, StringRef BaseName) const {
4102 SmallString<128> Output;
4103 if (Arg *FpArg = C.getArgs().getLastArg(options::OPT__SLASH_Fp)) {
4104 // FIXME: If anybody needs it, implement this obscure rule:
4105 // "If you specify a directory without a file name, the default file name
4106 // is VCx0.pch., where x is the major version of Visual C++ in use."
4107 Output = FpArg->getValue();
4108
4109 // "If you do not specify an extension as part of the path name, an
4110 // extension of .pch is assumed. "
4111 if (!llvm::sys::path::has_extension(Output))
4112 Output += ".pch";
4113 } else {
4114 Output = BaseName;
4115 llvm::sys::path::replace_extension(Output, ".pch");
4116 }
4117 return Output.str();
4118}
4119
Chandler Carruth2ad5de12012-01-25 11:01:57 +00004120const ToolChain &Driver::getToolChain(const ArgList &Args,
Artem Belevich959e0542015-07-10 19:47:55 +00004121 const llvm::Triple &Target) const {
Chandler Carruth2ad5de12012-01-25 11:01:57 +00004122
David Blaikie6ad71012017-01-13 18:53:43 +00004123 auto &TC = ToolChains[Target.str()];
Chandler Carruth2ad5de12012-01-25 11:01:57 +00004124 if (!TC) {
4125 switch (Target.getOS()) {
Reid Kleckner330fb172016-05-11 16:19:05 +00004126 case llvm::Triple::Haiku:
David Blaikie6ad71012017-01-13 18:53:43 +00004127 TC = llvm::make_unique<toolchains::Haiku>(*this, Target, Args);
Reid Kleckner330fb172016-05-11 16:19:05 +00004128 break;
Ed Schouten4dabea22017-06-25 08:29:09 +00004129 case llvm::Triple::Ananas:
4130 TC = llvm::make_unique<toolchains::Ananas>(*this, Target, Args);
4131 break;
Ed Schouten3c3e58c2015-03-26 11:13:44 +00004132 case llvm::Triple::CloudABI:
David Blaikie6ad71012017-01-13 18:53:43 +00004133 TC = llvm::make_unique<toolchains::CloudABI>(*this, Target, Args);
Ed Schouten3c3e58c2015-03-26 11:13:44 +00004134 break;
Chandler Carruth2ad5de12012-01-25 11:01:57 +00004135 case llvm::Triple::Darwin:
4136 case llvm::Triple::MacOSX:
4137 case llvm::Triple::IOS:
Tim Northover6f3ff222015-10-30 16:30:27 +00004138 case llvm::Triple::TvOS:
4139 case llvm::Triple::WatchOS:
David Blaikie6ad71012017-01-13 18:53:43 +00004140 TC = llvm::make_unique<toolchains::DarwinClang>(*this, Target, Args);
Chandler Carruth2ad5de12012-01-25 11:01:57 +00004141 break;
4142 case llvm::Triple::DragonFly:
David Blaikie6ad71012017-01-13 18:53:43 +00004143 TC = llvm::make_unique<toolchains::DragonFly>(*this, Target, Args);
Chandler Carruth2ad5de12012-01-25 11:01:57 +00004144 break;
4145 case llvm::Triple::OpenBSD:
David Blaikie6ad71012017-01-13 18:53:43 +00004146 TC = llvm::make_unique<toolchains::OpenBSD>(*this, Target, Args);
Chandler Carruth2ad5de12012-01-25 11:01:57 +00004147 break;
4148 case llvm::Triple::NetBSD:
David Blaikie6ad71012017-01-13 18:53:43 +00004149 TC = llvm::make_unique<toolchains::NetBSD>(*this, Target, Args);
Chandler Carruth2ad5de12012-01-25 11:01:57 +00004150 break;
4151 case llvm::Triple::FreeBSD:
David Blaikie6ad71012017-01-13 18:53:43 +00004152 TC = llvm::make_unique<toolchains::FreeBSD>(*this, Target, Args);
Chandler Carruth2ad5de12012-01-25 11:01:57 +00004153 break;
4154 case llvm::Triple::Minix:
David Blaikie6ad71012017-01-13 18:53:43 +00004155 TC = llvm::make_unique<toolchains::Minix>(*this, Target, Args);
Chandler Carruth2ad5de12012-01-25 11:01:57 +00004156 break;
4157 case llvm::Triple::Linux:
Andrey Turetskiy4798eb62016-06-16 10:36:09 +00004158 case llvm::Triple::ELFIAMCU:
Chandler Carruthcf705b22012-01-25 21:03:58 +00004159 if (Target.getArch() == llvm::Triple::hexagon)
David Blaikie6ad71012017-01-13 18:53:43 +00004160 TC = llvm::make_unique<toolchains::HexagonToolChain>(*this, Target,
4161 Args);
Vasileios Kalintirisc744e122015-11-12 15:26:54 +00004162 else if ((Target.getVendor() == llvm::Triple::MipsTechnologies) &&
4163 !Target.hasEnvironment())
David Blaikie6ad71012017-01-13 18:53:43 +00004164 TC = llvm::make_unique<toolchains::MipsLLVMToolChain>(*this, Target,
4165 Args);
Chandler Carruthcf705b22012-01-25 21:03:58 +00004166 else
David Blaikie6ad71012017-01-13 18:53:43 +00004167 TC = llvm::make_unique<toolchains::Linux>(*this, Target, Args);
Chandler Carruth2ad5de12012-01-25 11:01:57 +00004168 break;
Derek Schuff6ab52fa2015-03-30 20:31:33 +00004169 case llvm::Triple::NaCl:
David Blaikie6ad71012017-01-13 18:53:43 +00004170 TC = llvm::make_unique<toolchains::NaClToolChain>(*this, Target, Args);
Derek Schuff6ab52fa2015-03-30 20:31:33 +00004171 break;
Petr Hosek62e1d232016-10-06 06:08:09 +00004172 case llvm::Triple::Fuchsia:
David Blaikie6ad71012017-01-13 18:53:43 +00004173 TC = llvm::make_unique<toolchains::Fuchsia>(*this, Target, Args);
Petr Hosek62e1d232016-10-06 06:08:09 +00004174 break;
David Chisnallf571cde2012-02-15 13:39:01 +00004175 case llvm::Triple::Solaris:
David Blaikie6ad71012017-01-13 18:53:43 +00004176 TC = llvm::make_unique<toolchains::Solaris>(*this, Target, Args);
David Chisnallf571cde2012-02-15 13:39:01 +00004177 break;
Tom Stellard8fa33092015-07-18 01:49:05 +00004178 case llvm::Triple::AMDHSA:
David Blaikie6ad71012017-01-13 18:53:43 +00004179 TC = llvm::make_unique<toolchains::AMDGPUToolChain>(*this, Target, Args);
Tom Stellard8fa33092015-07-18 01:49:05 +00004180 break;
Chandler Carruth2ad5de12012-01-25 11:01:57 +00004181 case llvm::Triple::Win32:
Saleem Abdulrasool377066a2014-03-27 22:50:18 +00004182 switch (Target.getEnvironment()) {
4183 default:
4184 if (Target.isOSBinFormatELF())
David Blaikie6ad71012017-01-13 18:53:43 +00004185 TC = llvm::make_unique<toolchains::Generic_ELF>(*this, Target, Args);
Saleem Abdulrasool377066a2014-03-27 22:50:18 +00004186 else if (Target.isOSBinFormatMachO())
David Blaikie6ad71012017-01-13 18:53:43 +00004187 TC = llvm::make_unique<toolchains::MachO>(*this, Target, Args);
Saleem Abdulrasool377066a2014-03-27 22:50:18 +00004188 else
David Blaikie6ad71012017-01-13 18:53:43 +00004189 TC = llvm::make_unique<toolchains::Generic_GCC>(*this, Target, Args);
Saleem Abdulrasool377066a2014-03-27 22:50:18 +00004190 break;
4191 case llvm::Triple::GNU:
David Blaikie6ad71012017-01-13 18:53:43 +00004192 TC = llvm::make_unique<toolchains::MinGW>(*this, Target, Args);
Saleem Abdulrasool377066a2014-03-27 22:50:18 +00004193 break;
Saleem Abdulrasool543a78b2014-10-24 03:13:37 +00004194 case llvm::Triple::Itanium:
David Blaikie6ad71012017-01-13 18:53:43 +00004195 TC = llvm::make_unique<toolchains::CrossWindowsToolChain>(*this, Target,
4196 Args);
Saleem Abdulrasool543a78b2014-10-24 03:13:37 +00004197 break;
Saleem Abdulrasool377066a2014-03-27 22:50:18 +00004198 case llvm::Triple::MSVC:
4199 case llvm::Triple::UnknownEnvironment:
Dave Leef96bedf2017-11-06 21:18:05 +00004200 if (Args.getLastArgValue(options::OPT_fuse_ld_EQ)
4201 .startswith_lower("bfd"))
4202 TC = llvm::make_unique<toolchains::CrossWindowsToolChain>(
4203 *this, Target, Args);
4204 else
4205 TC =
4206 llvm::make_unique<toolchains::MSVCToolChain>(*this, Target, Args);
Saleem Abdulrasool377066a2014-03-27 22:50:18 +00004207 break;
4208 }
Chandler Carruth2ad5de12012-01-25 11:01:57 +00004209 break;
Filipe Cabecinhasc888e192015-10-14 12:25:43 +00004210 case llvm::Triple::PS4:
David Blaikie6ad71012017-01-13 18:53:43 +00004211 TC = llvm::make_unique<toolchains::PS4CPU>(*this, Target, Args);
Filipe Cabecinhasc888e192015-10-14 12:25:43 +00004212 break;
David L Kreitzerd397ea42016-10-14 20:44:33 +00004213 case llvm::Triple::Contiki:
David Blaikie6ad71012017-01-13 18:53:43 +00004214 TC = llvm::make_unique<toolchains::Contiki>(*this, Target, Args);
David L Kreitzerd397ea42016-10-14 20:44:33 +00004215 break;
Chandler Carruth2ad5de12012-01-25 11:01:57 +00004216 default:
Douglas Katzman9f5e70e2015-05-26 18:01:33 +00004217 // Of these targets, Hexagon is the only one that might have
4218 // an OS of Linux, in which case it got handled above already.
Douglas Katzman15a63ed2015-08-12 18:36:12 +00004219 switch (Target.getArch()) {
4220 case llvm::Triple::tce:
David Blaikie6ad71012017-01-13 18:53:43 +00004221 TC = llvm::make_unique<toolchains::TCEToolChain>(*this, Target, Args);
Douglas Katzman15a63ed2015-08-12 18:36:12 +00004222 break;
Pekka Jaaskelainen67354482016-11-16 15:22:31 +00004223 case llvm::Triple::tcele:
David Blaikie6ad71012017-01-13 18:53:43 +00004224 TC = llvm::make_unique<toolchains::TCELEToolChain>(*this, Target, Args);
Pekka Jaaskelainen67354482016-11-16 15:22:31 +00004225 break;
Douglas Katzman15a63ed2015-08-12 18:36:12 +00004226 case llvm::Triple::hexagon:
David Blaikie6ad71012017-01-13 18:53:43 +00004227 TC = llvm::make_unique<toolchains::HexagonToolChain>(*this, Target,
4228 Args);
Douglas Katzman15a63ed2015-08-12 18:36:12 +00004229 break;
Jacques Pienaard964cc22016-03-28 21:02:54 +00004230 case llvm::Triple::lanai:
David Blaikie6ad71012017-01-13 18:53:43 +00004231 TC = llvm::make_unique<toolchains::LanaiToolChain>(*this, Target, Args);
Jacques Pienaard964cc22016-03-28 21:02:54 +00004232 break;
Douglas Katzman15a63ed2015-08-12 18:36:12 +00004233 case llvm::Triple::xcore:
David Blaikie6ad71012017-01-13 18:53:43 +00004234 TC = llvm::make_unique<toolchains::XCoreToolChain>(*this, Target, Args);
Douglas Katzman15a63ed2015-08-12 18:36:12 +00004235 break;
Dan Gohmanc2853072015-09-03 22:51:53 +00004236 case llvm::Triple::wasm32:
4237 case llvm::Triple::wasm64:
David Blaikie6ad71012017-01-13 18:53:43 +00004238 TC = llvm::make_unique<toolchains::WebAssembly>(*this, Target, Args);
Dan Gohmanc2853072015-09-03 22:51:53 +00004239 break;
Dylan McKay924fa3a2017-01-05 05:20:27 +00004240 case llvm::Triple::avr:
David Blaikie6ad71012017-01-13 18:53:43 +00004241 TC = llvm::make_unique<toolchains::AVRToolChain>(*this, Target, Args);
Dylan McKay924fa3a2017-01-05 05:20:27 +00004242 break;
Douglas Katzman15a63ed2015-08-12 18:36:12 +00004243 default:
Douglas Katzmand6e597c2015-09-17 19:56:40 +00004244 if (Target.getVendor() == llvm::Triple::Myriad)
David Blaikie6ad71012017-01-13 18:53:43 +00004245 TC = llvm::make_unique<toolchains::MyriadToolChain>(*this, Target,
4246 Args);
Jonathan Roelofs901c7762017-05-25 15:42:13 +00004247 else if (toolchains::BareMetal::handlesTarget(Target))
4248 TC = llvm::make_unique<toolchains::BareMetal>(*this, Target, Args);
Douglas Katzmand6e597c2015-09-17 19:56:40 +00004249 else if (Target.isOSBinFormatELF())
David Blaikie6ad71012017-01-13 18:53:43 +00004250 TC = llvm::make_unique<toolchains::Generic_ELF>(*this, Target, Args);
Douglas Katzman15a63ed2015-08-12 18:36:12 +00004251 else if (Target.isOSBinFormatMachO())
David Blaikie6ad71012017-01-13 18:53:43 +00004252 TC = llvm::make_unique<toolchains::MachO>(*this, Target, Args);
Douglas Katzman15a63ed2015-08-12 18:36:12 +00004253 else
David Blaikie6ad71012017-01-13 18:53:43 +00004254 TC = llvm::make_unique<toolchains::Generic_GCC>(*this, Target, Args);
Douglas Katzman15a63ed2015-08-12 18:36:12 +00004255 }
Chandler Carruth2ad5de12012-01-25 11:01:57 +00004256 }
4257 }
Justin Lebar66c4fd72016-11-18 00:41:22 +00004258
4259 // Intentionally omitted from the switch above: llvm::Triple::CUDA. CUDA
4260 // compiles always need two toolchains, the CUDA toolchain and the host
4261 // toolchain. So the only valid way to create a CUDA toolchain is via
4262 // CreateOffloadingDeviceToolChains.
4263
Chandler Carruth2ad5de12012-01-25 11:01:57 +00004264 return *TC;
Daniel Dunbar4dff6a42009-03-10 23:41:59 +00004265}
Daniel Dunbar8fa879d2009-03-24 18:57:02 +00004266
Rafael Espindola2f69d402013-03-18 15:33:26 +00004267bool Driver::ShouldUseClangCompiler(const JobAction &JA) const {
Douglas Katzman00249092015-06-12 15:45:21 +00004268 // Say "no" if there is not exactly one input of a type clang understands.
Nico Weber5a459f82016-02-23 19:30:43 +00004269 if (JA.size() != 1 ||
4270 !types::isAcceptedByClang((*JA.input_begin())->getType()))
Nick Lewycky5cc9ebb2012-11-15 05:36:36 +00004271 return false;
4272
Douglas Katzman00249092015-06-12 15:45:21 +00004273 // And say "no" if this is not a kind of action clang understands.
Nick Lewycky5cc9ebb2012-11-15 05:36:36 +00004274 if (!isa<PreprocessJobAction>(JA) && !isa<PrecompileJobAction>(JA) &&
Bob Wilson23a55f12014-12-21 07:00:00 +00004275 !isa<CompileJobAction>(JA) && !isa<BackendJobAction>(JA))
Nick Lewycky5cc9ebb2012-11-15 05:36:36 +00004276 return false;
4277
4278 return true;
4279}
4280
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00004281/// GetReleaseVersion - Parse (([0-9]+)(.([0-9]+)(.([0-9]+)?))?)? and return the
4282/// grouped values as integers. Numbers which are not provided are set to 0.
Daniel Dunbarc7fd57a2009-03-26 15:58:36 +00004283///
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00004284/// \return True if the entire string was parsed (9.2), or all groups were
4285/// parsed (10.3.5extrastuff).
Mehdi Amini12011172016-10-06 05:11:48 +00004286bool Driver::GetReleaseVersion(StringRef Str, unsigned &Major, unsigned &Minor,
4287 unsigned &Micro, bool &HadExtra) {
Daniel Dunbarc7fd57a2009-03-26 15:58:36 +00004288 HadExtra = false;
4289
4290 Major = Minor = Micro = 0;
Mehdi Amini12011172016-10-06 05:11:48 +00004291 if (Str.empty())
Bob Wilson433cb312015-04-07 01:03:35 +00004292 return false;
Daniel Dunbarc7fd57a2009-03-26 15:58:36 +00004293
Mehdi Amini12011172016-10-06 05:11:48 +00004294 if (Str.consumeInteger(10, Major))
4295 return false;
4296 if (Str.empty())
Daniel Dunbarc7fd57a2009-03-26 15:58:36 +00004297 return true;
Mehdi Amini12011172016-10-06 05:11:48 +00004298 if (Str[0] != '.')
Daniel Dunbarc7fd57a2009-03-26 15:58:36 +00004299 return false;
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00004300
Mehdi Amini12011172016-10-06 05:11:48 +00004301 Str = Str.drop_front(1);
Daniel Dunbarc7fd57a2009-03-26 15:58:36 +00004302
Mehdi Amini12011172016-10-06 05:11:48 +00004303 if (Str.consumeInteger(10, Minor))
Daniel Dunbarc7fd57a2009-03-26 15:58:36 +00004304 return false;
Mehdi Amini12011172016-10-06 05:11:48 +00004305 if (Str.empty())
4306 return true;
4307 if (Str[0] != '.')
4308 return false;
4309 Str = Str.drop_front(1);
4310
4311 if (Str.consumeInteger(10, Micro))
4312 return false;
4313 if (!Str.empty())
4314 HadExtra = true;
Daniel Dunbarc7fd57a2009-03-26 15:58:36 +00004315 return true;
4316}
Hans Wennborg6ddc6902013-07-27 00:23:45 +00004317
Bruno Cardoso Lopes8ed5cac2016-03-31 02:45:46 +00004318/// Parse digits from a string \p Str and fulfill \p Digits with
4319/// the parsed numbers. This method assumes that the max number of
4320/// digits to look for is equal to Digits.size().
4321///
4322/// \return True if the entire string was parsed and there are
4323/// no extra characters remaining at the end.
Mehdi Amini12011172016-10-06 05:11:48 +00004324bool Driver::GetReleaseVersion(StringRef Str,
Bruno Cardoso Lopes8ed5cac2016-03-31 02:45:46 +00004325 MutableArrayRef<unsigned> Digits) {
Mehdi Amini12011172016-10-06 05:11:48 +00004326 if (Str.empty())
Bruno Cardoso Lopes8ed5cac2016-03-31 02:45:46 +00004327 return false;
4328
Bruno Cardoso Lopes8ed5cac2016-03-31 02:45:46 +00004329 unsigned CurDigit = 0;
4330 while (CurDigit < Digits.size()) {
Mehdi Amini12011172016-10-06 05:11:48 +00004331 unsigned Digit;
4332 if (Str.consumeInteger(10, Digit))
Bruno Cardoso Lopes8ed5cac2016-03-31 02:45:46 +00004333 return false;
Mehdi Amini12011172016-10-06 05:11:48 +00004334 Digits[CurDigit] = Digit;
4335 if (Str.empty())
4336 return true;
4337 if (Str[0] != '.')
4338 return false;
4339 Str = Str.drop_front(1);
Bruno Cardoso Lopes8ed5cac2016-03-31 02:45:46 +00004340 CurDigit++;
4341 }
4342
4343 // More digits than requested, bail out...
4344 return false;
4345}
4346
Hans Wennborg6ddc6902013-07-27 00:23:45 +00004347std::pair<unsigned, unsigned> Driver::getIncludeExcludeOptionFlagMasks() const {
4348 unsigned IncludedFlagsBitmask = 0;
Rafael Espindolacc707bc2013-09-25 15:54:41 +00004349 unsigned ExcludedFlagsBitmask = options::NoDriverOption;
Hans Wennborg6ddc6902013-07-27 00:23:45 +00004350
4351 if (Mode == CLMode) {
Hans Wennborg19076102013-07-31 20:51:53 +00004352 // Include CL and Core options.
4353 IncludedFlagsBitmask |= options::CLOption;
4354 IncludedFlagsBitmask |= options::CoreOption;
Hans Wennborg6ddc6902013-07-27 00:23:45 +00004355 } else {
4356 ExcludedFlagsBitmask |= options::CLOption;
4357 }
4358
4359 return std::make_pair(IncludedFlagsBitmask, ExcludedFlagsBitmask);
4360}
Benjamin Kramerab88f622014-03-25 18:02:07 +00004361
Douglas Katzmanf08fadf2015-06-04 14:40:44 +00004362bool clang::driver::isOptimizationLevelFast(const ArgList &Args) {
Benjamin Kramerab88f622014-03-25 18:02:07 +00004363 return Args.hasFlag(options::OPT_Ofast, options::OPT_O_Group, false);
4364}