blob: ad65f6f61e5e3cc0d2332253a7b9285e3eb1a5b7 [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),
Nico Webere0c3f902017-07-23 16:31:47 +000092 SysRoot(DEFAULT_SYSROOT),
Reid Kleckner68eb60b2015-02-02 22:41:48 +000093 DriverTitle("clang LLVM compiler"), CCPrintOptionsFilename(nullptr),
94 CCPrintHeadersFilename(nullptr), CCLogDiagnosticsFilename(nullptr),
95 CCCPrintBindings(false), CCPrintHeaders(false), CCLogDiagnostics(false),
Vedant Kumarf2030b92016-07-18 19:56:33 +000096 CCGenDiagnostics(false), DefaultTargetTriple(DefaultTargetTriple),
Serge Pavlov208ac652018-01-01 13:27:01 +000097 CCCGenericGCCName(""), Saver(Alloc),
98 CheckInputsExist(true), CCCUsePCH(true),
Bruno Cardoso Lopes52dfe712017-04-12 21:46:20 +000099 GenReproducer(false), 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) {
Serge Pavlov4e769842017-08-29 05:22:26 +0000132 ClangNameParts = ToolChain::getTargetAndModeFromProgramName(ProgramName);
133 setDriverModeFromOption(ClangNameParts.DriverMode);
Hans Wennborg70850d82013-07-18 20:29:38 +0000134
Douglas Katzman6bbffc42015-06-25 18:51:37 +0000135 for (const char *ArgPtr : Args) {
Erich Keane258f0592018-02-07 00:19:58 +0000136 // Ignore nullptrs, they are the response file's EOL markers.
Douglas Katzman6bbffc42015-06-25 18:51:37 +0000137 if (ArgPtr == nullptr)
Reid Kleckneraf5fd6a2014-08-22 19:29:30 +0000138 continue;
Douglas Katzman6bbffc42015-06-25 18:51:37 +0000139 const StringRef Arg = ArgPtr;
Zachary Turneraff19c32016-08-12 17:47:52 +0000140 setDriverModeFromOption(Arg);
Hans Wennborg70850d82013-07-18 20:29:38 +0000141 }
142}
143
Zachary Turneraff19c32016-08-12 17:47:52 +0000144void Driver::setDriverModeFromOption(StringRef Opt) {
145 const std::string OptName =
146 getOpts().getOption(options::OPT_driver_mode).getPrefixedName();
147 if (!Opt.startswith(OptName))
148 return;
149 StringRef Value = Opt.drop_front(OptName.size());
150
Erich Keane2908a042018-02-12 17:47:01 +0000151 if (auto M = llvm::StringSwitch<llvm::Optional<DriverMode>>(Value)
152 .Case("gcc", GCCMode)
153 .Case("g++", GXXMode)
154 .Case("cpp", CPPMode)
155 .Case("cl", CLMode)
156 .Default(None))
157 Mode = *M;
Zachary Turneraff19c32016-08-12 17:47:52 +0000158 else
159 Diag(diag::err_drv_unsupported_option_argument) << OptName << Value;
160}
161
Benjamin Kramer43c0f482017-06-30 13:21:27 +0000162InputArgList Driver::ParseArgStrings(ArrayRef<const char *> ArgStrings,
163 bool &ContainsError) {
Daniel Dunbar2608c542009-03-18 01:38:48 +0000164 llvm::PrettyStackTraceString CrashInfo("Command line argument parsing");
Benjamin Kramer43c0f482017-06-30 13:21:27 +0000165 ContainsError = false;
Hans Wennborg6ddc6902013-07-27 00:23:45 +0000166
167 unsigned IncludedFlagsBitmask;
168 unsigned ExcludedFlagsBitmask;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +0000169 std::tie(IncludedFlagsBitmask, ExcludedFlagsBitmask) =
Douglas Katzmana67e50c2015-06-26 15:47:46 +0000170 getIncludeExcludeOptionFlagMasks();
Hans Wennborg6ddc6902013-07-27 00:23:45 +0000171
Daniel Dunbar52ed5fe2009-11-19 06:35:06 +0000172 unsigned MissingArgIndex, MissingArgCount;
David Blaikie69a1d8c2015-06-22 22:07:27 +0000173 InputArgList Args =
David Blaikie6d492ad2015-06-21 06:32:36 +0000174 getOpts().ParseArgs(ArgStrings, MissingArgIndex, MissingArgCount,
175 IncludedFlagsBitmask, ExcludedFlagsBitmask);
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +0000176
Daniel Dunbar52ed5fe2009-11-19 06:35:06 +0000177 // Check for missing argument error.
Benjamin Kramer43c0f482017-06-30 13:21:27 +0000178 if (MissingArgCount) {
179 Diag(diag::err_drv_missing_argument)
David Blaikie69a1d8c2015-06-22 22:07:27 +0000180 << Args.getArgString(MissingArgIndex) << MissingArgCount;
Benjamin Kramer43c0f482017-06-30 13:21:27 +0000181 ContainsError |=
182 Diags.getDiagnosticLevel(diag::err_drv_missing_argument,
183 SourceLocation()) > DiagnosticsEngine::Warning;
184 }
Daniel Dunbar65229332009-03-13 11:38:42 +0000185
Daniel Dunbar52ed5fe2009-11-19 06:35:06 +0000186 // Check for unsupported options.
David Blaikie69a1d8c2015-06-22 22:07:27 +0000187 for (const Arg *A : Args) {
Michael J. Spencer66e2b202012-10-19 22:37:06 +0000188 if (A->getOption().hasFlag(options::Unsupported)) {
Brian Gesiak24910762018-01-06 00:25:40 +0000189 unsigned DiagID;
190 auto ArgString = A->getAsString(Args);
191 std::string Nearest;
192 if (getOpts().findNearest(
193 ArgString, Nearest, IncludedFlagsBitmask,
194 ExcludedFlagsBitmask | options::Unsupported) > 1) {
195 DiagID = diag::err_drv_unsupported_opt;
196 Diag(DiagID) << ArgString;
197 } else {
198 DiagID = diag::err_drv_unsupported_opt_with_suggestion;
199 Diag(DiagID) << ArgString << Nearest;
200 }
201 ContainsError |= Diags.getDiagnosticLevel(DiagID, SourceLocation()) >
Benjamin Kramer43c0f482017-06-30 13:21:27 +0000202 DiagnosticsEngine::Warning;
Daniel Dunbard8500f32009-03-22 23:26:43 +0000203 continue;
204 }
Chad Rosierce975d92012-02-22 17:55:22 +0000205
206 // Warn about -mcpu= without an argument.
Douglas Katzmana67e50c2015-06-26 15:47:46 +0000207 if (A->getOption().matches(options::OPT_mcpu_EQ) && A->containsValue("")) {
Benjamin Kramer43c0f482017-06-30 13:21:27 +0000208 Diag(diag::warn_drv_empty_joined_argument) << A->getAsString(Args);
209 ContainsError |= Diags.getDiagnosticLevel(
210 diag::warn_drv_empty_joined_argument,
211 SourceLocation()) > DiagnosticsEngine::Warning;
Chad Rosierce975d92012-02-22 17:55:22 +0000212 }
Daniel Dunbard02cb1d2009-03-05 06:38:47 +0000213 }
214
Benjamin Kramer43c0f482017-06-30 13:21:27 +0000215 for (const Arg *A : Args.filtered(options::OPT_UNKNOWN)) {
Brian Gesiak24910762018-01-06 00:25:40 +0000216 unsigned DiagID;
217 auto ArgString = A->getAsString(Args);
218 std::string Nearest;
219 if (getOpts().findNearest(
220 ArgString, Nearest, IncludedFlagsBitmask, ExcludedFlagsBitmask) > 1) {
221 DiagID = IsCLMode() ? diag::warn_drv_unknown_argument_clang_cl
222 : diag::err_drv_unknown_argument;
223 Diags.Report(DiagID) << ArgString;
224 } else {
225 DiagID = IsCLMode() ? diag::warn_drv_unknown_argument_clang_cl_with_suggestion
226 : diag::err_drv_unknown_argument_with_suggestion;
227 Diags.Report(DiagID) << ArgString << Nearest;
228 }
229 ContainsError |= Diags.getDiagnosticLevel(DiagID, SourceLocation()) >
Benjamin Kramer43c0f482017-06-30 13:21:27 +0000230 DiagnosticsEngine::Warning;
231 }
Rafael Espindola8a2d4962013-09-23 23:55:25 +0000232
Daniel Dunbard02cb1d2009-03-05 06:38:47 +0000233 return Args;
234}
235
Chad Rosier7742b5d2011-07-27 23:36:45 +0000236// Determine which compilation mode we are in. We look for options which
237// affect the phase, starting with the earliest phases, and record which
238// option we used to determine the final phase.
Douglas Katzmana67e50c2015-06-26 15:47:46 +0000239phases::ID Driver::getFinalPhase(const DerivedArgList &DAL,
240 Arg **FinalPhaseArg) const {
Craig Topper92fc2df2014-05-17 16:56:41 +0000241 Arg *PhaseArg = nullptr;
Chad Rosier7742b5d2011-07-27 23:36:45 +0000242 phases::ID FinalPhase;
Eric Christopherf901e852011-08-17 22:59:59 +0000243
Hans Wennborge50cec32014-06-13 20:59:54 +0000244 // -{E,EP,P,M,MM} only run the preprocessor.
Douglas Katzmana67e50c2015-06-26 15:47:46 +0000245 if (CCCIsCPP() || (PhaseArg = DAL.getLastArg(options::OPT_E)) ||
Hans Wennborge50cec32014-06-13 20:59:54 +0000246 (PhaseArg = DAL.getLastArg(options::OPT__SLASH_EP)) ||
Hans Wennborge0053472013-12-20 18:40:46 +0000247 (PhaseArg = DAL.getLastArg(options::OPT_M, options::OPT_MM)) ||
248 (PhaseArg = DAL.getLastArg(options::OPT__SLASH_P))) {
Chad Rosier7742b5d2011-07-27 23:36:45 +0000249 FinalPhase = phases::Preprocess;
Eric Christopherf901e852011-08-17 22:59:59 +0000250
Richard Smithdd4ad3d2016-08-30 19:06:26 +0000251 // --precompile only runs up to precompilation.
252 } else if ((PhaseArg = DAL.getLastArg(options::OPT__precompile))) {
253 FinalPhase = phases::Precompile;
254
Bob Wilson23a55f12014-12-21 07:00:00 +0000255 // -{fsyntax-only,-analyze,emit-ast} only run up to the compiler.
Chad Rosier7742b5d2011-07-27 23:36:45 +0000256 } else if ((PhaseArg = DAL.getLastArg(options::OPT_fsyntax_only)) ||
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +0000257 (PhaseArg = DAL.getLastArg(options::OPT_module_file_info)) ||
Ben Langmuir2cb4a782014-02-05 22:21:15 +0000258 (PhaseArg = DAL.getLastArg(options::OPT_verify_pch)) ||
Chad Rosier7742b5d2011-07-27 23:36:45 +0000259 (PhaseArg = DAL.getLastArg(options::OPT_rewrite_objc)) ||
Fariborz Jahanian73223bb2012-04-02 15:59:19 +0000260 (PhaseArg = DAL.getLastArg(options::OPT_rewrite_legacy_objc)) ||
Ted Kremenekf7639e12012-03-06 20:06:33 +0000261 (PhaseArg = DAL.getLastArg(options::OPT__migrate)) ||
Chad Rosier7742b5d2011-07-27 23:36:45 +0000262 (PhaseArg = DAL.getLastArg(options::OPT__analyze,
Chad Rosier1aeb15a2012-03-06 23:14:35 +0000263 options::OPT__analyze_auto)) ||
Bob Wilson23a55f12014-12-21 07:00:00 +0000264 (PhaseArg = DAL.getLastArg(options::OPT_emit_ast))) {
Chad Rosier7742b5d2011-07-27 23:36:45 +0000265 FinalPhase = phases::Compile;
266
Bob Wilson23a55f12014-12-21 07:00:00 +0000267 // -S only runs up to the backend.
268 } else if ((PhaseArg = DAL.getLastArg(options::OPT_S))) {
269 FinalPhase = phases::Backend;
270
Artem Belevich4242f412015-07-28 21:01:21 +0000271 // -c compilation only runs up to the assembler.
272 } else if ((PhaseArg = DAL.getLastArg(options::OPT_c))) {
Chad Rosier7742b5d2011-07-27 23:36:45 +0000273 FinalPhase = phases::Assemble;
274
275 // Otherwise do everything.
276 } else
277 FinalPhase = phases::Link;
278
279 if (FinalPhaseArg)
280 *FinalPhaseArg = PhaseArg;
281
282 return FinalPhase;
283}
284
David Blaikie0aaa7622017-01-13 17:34:15 +0000285static Arg *MakeInputArg(DerivedArgList &Args, OptTable &Opts,
Hans Wennborged1d0722013-08-13 21:32:29 +0000286 StringRef Value) {
David Blaikie0aaa7622017-01-13 17:34:15 +0000287 Arg *A = new Arg(Opts.getOption(options::OPT_INPUT), Value,
Hans Wennborged1d0722013-08-13 21:32:29 +0000288 Args.getBaseArgs().MakeIndex(Value), Value.data());
Hans Wennborg55362852014-05-02 22:55:30 +0000289 Args.AddSynthesizedArg(A);
Hans Wennborged1d0722013-08-13 21:32:29 +0000290 A->claim();
291 return A;
292}
293
Daniel Dunbar775d4062010-06-11 22:00:26 +0000294DerivedArgList *Driver::TranslateInputArgs(const InputArgList &Args) const {
295 DerivedArgList *DAL = new DerivedArgList(Args);
296
Daniel Dunbar2cc3f172010-09-17 00:45:02 +0000297 bool HasNostdlib = Args.hasArg(options::OPT_nostdlib);
Nirav Daveb0bb6142015-11-24 16:07:21 +0000298 bool HasNodefaultlib = Args.hasArg(options::OPT_nodefaultlibs);
Saleem Abdulrasool688b6bc2014-12-29 19:01:36 +0000299 for (Arg *A : Args) {
Daniel Dunbarfb3d7472010-06-14 21:23:12 +0000300 // Unfortunately, we have to parse some forwarding options (-Xassembler,
301 // -Xlinker, -Xpreprocessor) because we either integrate their functionality
302 // (assembler and preprocessor), or bypass a previous driver ('collect2').
Daniel Dunbar5a9d1832010-06-14 21:37:09 +0000303
304 // Rewrite linker options, to replace --no-demangle with a custom internal
305 // option.
306 if ((A->getOption().matches(options::OPT_Wl_COMMA) ||
307 A->getOption().matches(options::OPT_Xlinker)) &&
308 A->containsValue("--no-demangle")) {
Daniel Dunbarfb3d7472010-06-14 21:23:12 +0000309 // Add the rewritten no-demangle argument.
310 DAL->AddFlagArg(A, Opts->getOption(options::OPT_Z_Xlinker__no_demangle));
311
312 // Add the remaining values as Xlinker arguments.
Benjamin Kramer72e64312015-09-24 14:48:49 +0000313 for (StringRef Val : A->getValues())
Douglas Katzmana34b7bf2015-06-30 19:32:57 +0000314 if (Val != "--no-demangle")
315 DAL->AddSeparateArg(A, Opts->getOption(options::OPT_Xlinker), Val);
Daniel Dunbarfb3d7472010-06-14 21:23:12 +0000316
317 continue;
318 }
319
Daniel Dunbar5a9d1832010-06-14 21:37:09 +0000320 // Rewrite preprocessor options, to replace -Wp,-MD,FOO which is used by
321 // some build systems. We don't try to be complete here because we don't
322 // care to encourage this usage model.
323 if (A->getOption().matches(options::OPT_Wp_COMMA) &&
Richard Smithbd55daf2012-11-01 04:30:05 +0000324 (A->getValue(0) == StringRef("-MD") ||
325 A->getValue(0) == StringRef("-MMD"))) {
Daniel Dunbar3648ba72010-06-15 20:30:18 +0000326 // Rewrite to -MD/-MMD along with -MF.
Richard Smithbd55daf2012-11-01 04:30:05 +0000327 if (A->getValue(0) == StringRef("-MD"))
Daniel Dunbar3648ba72010-06-15 20:30:18 +0000328 DAL->AddFlagArg(A, Opts->getOption(options::OPT_MD));
329 else
330 DAL->AddFlagArg(A, Opts->getOption(options::OPT_MMD));
Michael J. Spencer70d85be2012-11-07 23:37:14 +0000331 if (A->getNumValues() == 2)
332 DAL->AddSeparateArg(A, Opts->getOption(options::OPT_MF),
333 A->getValue(1));
Daniel Dunbar5a9d1832010-06-14 21:37:09 +0000334 continue;
335 }
336
Shantonu Senafeb03b2010-09-17 18:39:08 +0000337 // Rewrite reserved library names.
338 if (A->getOption().matches(options::OPT_l)) {
Richard Smithbd55daf2012-11-01 04:30:05 +0000339 StringRef Value = A->getValue();
Daniel Dunbar2cc3f172010-09-17 00:45:02 +0000340
Shantonu Senafeb03b2010-09-17 18:39:08 +0000341 // Rewrite unless -nostdlib is present.
Nirav Daveb0bb6142015-11-24 16:07:21 +0000342 if (!HasNostdlib && !HasNodefaultlib && Value == "stdc++") {
Douglas Katzmana67e50c2015-06-26 15:47:46 +0000343 DAL->AddFlagArg(A, Opts->getOption(options::OPT_Z_reserved_lib_stdcxx));
Daniel Dunbar2cc3f172010-09-17 00:45:02 +0000344 continue;
345 }
Shantonu Senafeb03b2010-09-17 18:39:08 +0000346
347 // Rewrite unconditionally.
348 if (Value == "cc_kext") {
Douglas Katzmana67e50c2015-06-26 15:47:46 +0000349 DAL->AddFlagArg(A, Opts->getOption(options::OPT_Z_reserved_lib_cckext));
Shantonu Senafeb03b2010-09-17 18:39:08 +0000350 continue;
351 }
Daniel Dunbar2cc3f172010-09-17 00:45:02 +0000352 }
353
Hans Wennborged1d0722013-08-13 21:32:29 +0000354 // Pick up inputs via the -- option.
355 if (A->getOption().matches(options::OPT__DASH_DASH)) {
356 A->claim();
Benjamin Kramer72e64312015-09-24 14:48:49 +0000357 for (StringRef Val : A->getValues())
David Blaikie0aaa7622017-01-13 17:34:15 +0000358 DAL->append(MakeInputArg(*DAL, *Opts, Val));
Hans Wennborged1d0722013-08-13 21:32:29 +0000359 continue;
360 }
361
Saleem Abdulrasool688b6bc2014-12-29 19:01:36 +0000362 DAL->append(A);
Daniel Dunbarfb3d7472010-06-14 21:23:12 +0000363 }
Daniel Dunbar775d4062010-06-11 22:00:26 +0000364
Andrey Turetskiy6a8b91d2016-04-21 10:16:48 +0000365 // Enforce -static if -miamcu is present.
Andrey Turetskiy5fea71c2016-06-29 10:57:17 +0000366 if (Args.hasFlag(options::OPT_miamcu, options::OPT_mno_iamcu, false))
367 DAL->AddFlagArg(0, Opts->getOption(options::OPT_static));
Andrey Turetskiy6a8b91d2016-04-21 10:16:48 +0000368
Douglas Katzmana67e50c2015-06-26 15:47:46 +0000369// Add a default value of -mlinker-version=, if one was given and the user
370// didn't specify one.
Daniel Dunbar628fcf42010-08-12 00:05:12 +0000371#if defined(HOST_LINK_VERSION)
Tim Northover018578c2015-06-12 19:21:35 +0000372 if (!Args.hasArg(options::OPT_mlinker_version_EQ) &&
373 strlen(HOST_LINK_VERSION) > 0) {
Daniel Dunbar628fcf42010-08-12 00:05:12 +0000374 DAL->AddJoinedArg(0, Opts->getOption(options::OPT_mlinker_version_EQ),
375 HOST_LINK_VERSION);
Daniel Dunbarb613ffc2010-08-17 22:32:45 +0000376 DAL->getLastArg(options::OPT_mlinker_version_EQ)->claim();
Daniel Dunbar628fcf42010-08-12 00:05:12 +0000377 }
378#endif
379
Daniel Dunbar775d4062010-06-11 22:00:26 +0000380 return DAL;
381}
382
Artem Belevich959e0542015-07-10 19:47:55 +0000383/// \brief Compute target triple from args.
384///
385/// This routine provides the logic to compute a target triple from various
386/// args passed to the driver and the default triple string.
Andrey Turetskiy6a8b91d2016-04-21 10:16:48 +0000387static llvm::Triple computeTargetTriple(const Driver &D,
388 StringRef DefaultTargetTriple,
Artem Belevich959e0542015-07-10 19:47:55 +0000389 const ArgList &Args,
390 StringRef DarwinArchName = "") {
391 // FIXME: Already done in Compilation *Driver::BuildCompilation
392 if (const Arg *A = Args.getLastArg(options::OPT_target))
393 DefaultTargetTriple = A->getValue();
394
395 llvm::Triple Target(llvm::Triple::normalize(DefaultTargetTriple));
396
397 // Handle Apple-specific options available here.
398 if (Target.isOSBinFormatMachO()) {
399 // If an explict Darwin arch name is given, that trumps all.
400 if (!DarwinArchName.empty()) {
401 tools::darwin::setTripleTypeForMachOArchName(Target, DarwinArchName);
402 return Target;
403 }
404
405 // Handle the Darwin '-arch' flag.
406 if (Arg *A = Args.getLastArg(options::OPT_arch)) {
407 StringRef ArchName = A->getValue();
408 tools::darwin::setTripleTypeForMachOArchName(Target, ArchName);
409 }
410 }
411
412 // Handle pseudo-target flags '-mlittle-endian'/'-EL' and
413 // '-mbig-endian'/'-EB'.
414 if (Arg *A = Args.getLastArg(options::OPT_mlittle_endian,
415 options::OPT_mbig_endian)) {
416 if (A->getOption().matches(options::OPT_mlittle_endian)) {
417 llvm::Triple LE = Target.getLittleEndianArchVariant();
418 if (LE.getArch() != llvm::Triple::UnknownArch)
419 Target = std::move(LE);
420 } else {
421 llvm::Triple BE = Target.getBigEndianArchVariant();
422 if (BE.getArch() != llvm::Triple::UnknownArch)
423 Target = std::move(BE);
424 }
425 }
426
427 // Skip further flag support on OSes which don't support '-m32' or '-m64'.
Douglas Katzman15a63ed2015-08-12 18:36:12 +0000428 if (Target.getArch() == llvm::Triple::tce ||
429 Target.getOS() == llvm::Triple::Minix)
Artem Belevich959e0542015-07-10 19:47:55 +0000430 return Target;
431
432 // Handle pseudo-target flags '-m64', '-mx32', '-m32' and '-m16'.
Andrey Turetskiy6a8b91d2016-04-21 10:16:48 +0000433 Arg *A = Args.getLastArg(options::OPT_m64, options::OPT_mx32,
434 options::OPT_m32, options::OPT_m16);
435 if (A) {
Artem Belevich959e0542015-07-10 19:47:55 +0000436 llvm::Triple::ArchType AT = llvm::Triple::UnknownArch;
437
438 if (A->getOption().matches(options::OPT_m64)) {
439 AT = Target.get64BitArchVariant().getArch();
440 if (Target.getEnvironment() == llvm::Triple::GNUX32)
441 Target.setEnvironment(llvm::Triple::GNU);
442 } else if (A->getOption().matches(options::OPT_mx32) &&
443 Target.get64BitArchVariant().getArch() == llvm::Triple::x86_64) {
444 AT = llvm::Triple::x86_64;
445 Target.setEnvironment(llvm::Triple::GNUX32);
446 } else if (A->getOption().matches(options::OPT_m32)) {
447 AT = Target.get32BitArchVariant().getArch();
448 if (Target.getEnvironment() == llvm::Triple::GNUX32)
449 Target.setEnvironment(llvm::Triple::GNU);
450 } else if (A->getOption().matches(options::OPT_m16) &&
451 Target.get32BitArchVariant().getArch() == llvm::Triple::x86) {
452 AT = llvm::Triple::x86;
453 Target.setEnvironment(llvm::Triple::CODE16);
454 }
455
456 if (AT != llvm::Triple::UnknownArch && AT != Target.getArch())
457 Target.setArch(AT);
458 }
459
Andrey Turetskiy6a8b91d2016-04-21 10:16:48 +0000460 // Handle -miamcu flag.
Andrey Turetskiy5fea71c2016-06-29 10:57:17 +0000461 if (Args.hasFlag(options::OPT_miamcu, options::OPT_mno_iamcu, false)) {
462 if (Target.get32BitArchVariant().getArch() != llvm::Triple::x86)
463 D.Diag(diag::err_drv_unsupported_opt_for_target) << "-miamcu"
464 << Target.str();
Andrey Turetskiy6a8b91d2016-04-21 10:16:48 +0000465
Andrey Turetskiy5fea71c2016-06-29 10:57:17 +0000466 if (A && !A->getOption().matches(options::OPT_m32))
467 D.Diag(diag::err_drv_argument_not_allowed_with)
468 << "-miamcu" << A->getBaseArg().getAsString(Args);
Andrey Turetskiy6a8b91d2016-04-21 10:16:48 +0000469
Andrey Turetskiy5fea71c2016-06-29 10:57:17 +0000470 Target.setArch(llvm::Triple::x86);
471 Target.setArchName("i586");
472 Target.setEnvironment(llvm::Triple::UnknownEnvironment);
473 Target.setEnvironmentName("");
474 Target.setOS(llvm::Triple::ELFIAMCU);
475 Target.setVendor(llvm::Triple::UnknownVendor);
476 Target.setVendorName("intel");
Andrey Turetskiy6a8b91d2016-04-21 10:16:48 +0000477 }
478
Artem Belevich959e0542015-07-10 19:47:55 +0000479 return Target;
480}
481
Teresa Johnson945bc502015-10-15 20:35:53 +0000482// \brief Parse the LTO options and record the type of LTO compilation
483// based on which -f(no-)?lto(=.*)? option occurs last.
484void Driver::setLTOMode(const llvm::opt::ArgList &Args) {
485 LTOMode = LTOK_None;
486 if (!Args.hasFlag(options::OPT_flto, options::OPT_flto_EQ,
487 options::OPT_fno_lto, false))
488 return;
489
490 StringRef LTOName("full");
491
492 const Arg *A = Args.getLastArg(options::OPT_flto_EQ);
Teresa Johnson6ef80dc2015-11-02 18:03:12 +0000493 if (A)
494 LTOName = A->getValue();
Teresa Johnson945bc502015-10-15 20:35:53 +0000495
496 LTOMode = llvm::StringSwitch<LTOKind>(LTOName)
497 .Case("full", LTOK_Full)
498 .Case("thin", LTOK_Thin)
499 .Default(LTOK_Unknown);
500
501 if (LTOMode == LTOK_Unknown) {
502 assert(A);
503 Diag(diag::err_drv_unsupported_option_argument) << A->getOption().getName()
504 << A->getValue();
505 }
506}
507
Samuel Antao39f9da22016-10-27 16:38:05 +0000508/// Compute the desired OpenMP runtime from the flags provided.
509Driver::OpenMPRuntimeKind Driver::getOpenMPRuntime(const ArgList &Args) const {
510 StringRef RuntimeName(CLANG_DEFAULT_OPENMP_RUNTIME);
511
512 const Arg *A = Args.getLastArg(options::OPT_fopenmp_EQ);
513 if (A)
514 RuntimeName = A->getValue();
515
516 auto RT = llvm::StringSwitch<OpenMPRuntimeKind>(RuntimeName)
517 .Case("libomp", OMPRT_OMP)
518 .Case("libgomp", OMPRT_GOMP)
519 .Case("libiomp5", OMPRT_IOMP5)
520 .Default(OMPRT_Unknown);
521
522 if (RT == OMPRT_Unknown) {
523 if (A)
524 Diag(diag::err_drv_unsupported_option_argument)
525 << A->getOption().getName() << A->getValue();
526 else
527 // FIXME: We could use a nicer diagnostic here.
528 Diag(diag::err_drv_unsupported_opt) << "-fopenmp";
529 }
530
531 return RT;
532}
533
Samuel Antaoc1ffba52016-06-13 18:10:57 +0000534void Driver::CreateOffloadingDeviceToolChains(Compilation &C,
535 InputList &Inputs) {
536
537 //
538 // CUDA
539 //
540 // We need to generate a CUDA toolchain if any of the inputs has a CUDA type.
541 if (llvm::any_of(Inputs, [](std::pair<types::ID, const llvm::opt::Arg *> &I) {
542 return types::isCuda(I.first);
543 })) {
Justin Lebar66c4fd72016-11-18 00:41:22 +0000544 const ToolChain *HostTC = C.getSingleOffloadToolChain<Action::OFK_Host>();
545 const llvm::Triple &HostTriple = HostTC->getTriple();
546 llvm::Triple CudaTriple(HostTriple.isArch64Bit() ? "nvptx64-nvidia-cuda"
547 : "nvptx-nvidia-cuda");
548 // Use the CUDA and host triples as the key into the ToolChains map, because
549 // the device toolchain we create depends on both.
David Blaikie6ad71012017-01-13 18:53:43 +0000550 auto &CudaTC = ToolChains[CudaTriple.str() + "/" + HostTriple.str()];
Justin Lebar66c4fd72016-11-18 00:41:22 +0000551 if (!CudaTC) {
David Blaikie6ad71012017-01-13 18:53:43 +0000552 CudaTC = llvm::make_unique<toolchains::CudaToolChain>(
Gheorghe-Teodor Bercea2c926932017-08-08 14:33:05 +0000553 *this, CudaTriple, *HostTC, C.getInputArgs(), Action::OFK_Cuda);
Justin Lebar66c4fd72016-11-18 00:41:22 +0000554 }
David Blaikie6ad71012017-01-13 18:53:43 +0000555 C.addOffloadDeviceToolChain(CudaTC.get(), Action::OFK_Cuda);
Samuel Antaoc1ffba52016-06-13 18:10:57 +0000556 }
557
558 //
Samuel Antao39f9da22016-10-27 16:38:05 +0000559 // OpenMP
560 //
561 // We need to generate an OpenMP toolchain if the user specified targets with
562 // the -fopenmp-targets option.
563 if (Arg *OpenMPTargets =
564 C.getInputArgs().getLastArg(options::OPT_fopenmp_targets_EQ)) {
565 if (OpenMPTargets->getNumValues()) {
566 // We expect that -fopenmp-targets is always used in conjunction with the
567 // option -fopenmp specifying a valid runtime with offloading support,
568 // i.e. libomp or libiomp.
569 bool HasValidOpenMPRuntime = C.getInputArgs().hasFlag(
570 options::OPT_fopenmp, options::OPT_fopenmp_EQ,
571 options::OPT_fno_openmp, false);
572 if (HasValidOpenMPRuntime) {
573 OpenMPRuntimeKind OpenMPKind = getOpenMPRuntime(C.getInputArgs());
574 HasValidOpenMPRuntime =
575 OpenMPKind == OMPRT_OMP || OpenMPKind == OMPRT_IOMP5;
576 }
577
578 if (HasValidOpenMPRuntime) {
579 llvm::StringMap<const char *> FoundNormalizedTriples;
580 for (const char *Val : OpenMPTargets->getValues()) {
581 llvm::Triple TT(Val);
582 std::string NormalizedName = TT.normalize();
583
584 // Make sure we don't have a duplicate triple.
585 auto Duplicate = FoundNormalizedTriples.find(NormalizedName);
586 if (Duplicate != FoundNormalizedTriples.end()) {
587 Diag(clang::diag::warn_drv_omp_offload_target_duplicate)
588 << Val << Duplicate->second;
589 continue;
590 }
591
592 // Store the current triple so that we can check for duplicates in the
593 // following iterations.
594 FoundNormalizedTriples[NormalizedName] = Val;
595
596 // If the specified target is invalid, emit a diagnostic.
597 if (TT.getArch() == llvm::Triple::UnknownArch)
598 Diag(clang::diag::err_drv_invalid_omp_target) << Val;
599 else {
Gheorghe-Teodor Bercea6a5df722017-07-06 16:08:15 +0000600 const ToolChain *TC;
601 // CUDA toolchains have to be selected differently. They pair host
602 // and device in their implementation.
603 if (TT.isNVPTX()) {
604 const ToolChain *HostTC =
605 C.getSingleOffloadToolChain<Action::OFK_Host>();
606 assert(HostTC && "Host toolchain should be always defined.");
607 auto &CudaTC =
Gheorghe-Teodor Bercea52898432017-08-09 01:02:19 +0000608 ToolChains[TT.str() + "/" + HostTC->getTriple().normalize()];
Gheorghe-Teodor Bercea6a5df722017-07-06 16:08:15 +0000609 if (!CudaTC)
610 CudaTC = llvm::make_unique<toolchains::CudaToolChain>(
Gheorghe-Teodor Bercea2c926932017-08-08 14:33:05 +0000611 *this, TT, *HostTC, C.getInputArgs(), Action::OFK_OpenMP);
Gheorghe-Teodor Bercea6a5df722017-07-06 16:08:15 +0000612 TC = CudaTC.get();
613 } else
614 TC = &getToolChain(C.getInputArgs(), TT);
615 C.addOffloadDeviceToolChain(TC, Action::OFK_OpenMP);
Samuel Antao39f9da22016-10-27 16:38:05 +0000616 }
617 }
618 } else
619 Diag(clang::diag::err_drv_expecting_fopenmp_with_fopenmp_targets);
620 } else
621 Diag(clang::diag::warn_drv_empty_joined_argument)
622 << OpenMPTargets->getAsString(C.getInputArgs());
623 }
624
625 //
Samuel Antaoc1ffba52016-06-13 18:10:57 +0000626 // TODO: Add support for other offloading programming models here.
627 //
Samuel Antaoc1ffba52016-06-13 18:10:57 +0000628}
629
Serge Pavlov208ac652018-01-01 13:27:01 +0000630/// Looks the given directories for the specified file.
631///
632/// \param[out] FilePath File path, if the file was found.
633/// \param[in] Dirs Directories used for the search.
634/// \param[in] FileName Name of the file to search for.
635/// \return True if file was found.
636///
637/// Looks for file specified by FileName sequentially in directories specified
638/// by Dirs.
639///
640static bool searchForFile(SmallVectorImpl<char> &FilePath,
641 ArrayRef<std::string> Dirs,
642 StringRef FileName) {
643 SmallString<128> WPath;
644 for (const StringRef &Dir : Dirs) {
645 if (Dir.empty())
646 continue;
647 WPath.clear();
648 llvm::sys::path::append(WPath, Dir, FileName);
649 llvm::sys::path::native(WPath);
650 if (llvm::sys::fs::is_regular_file(WPath)) {
651 FilePath = std::move(WPath);
652 return true;
653 }
654 }
655 return false;
656}
657
658bool Driver::readConfigFile(StringRef FileName) {
659 // Try reading the given file.
660 SmallVector<const char *, 32> NewCfgArgs;
661 if (!llvm::cl::readConfigFile(FileName, Saver, NewCfgArgs)) {
662 Diag(diag::err_drv_cannot_read_config_file) << FileName;
663 return true;
664 }
665
666 // Read options from config file.
667 llvm::SmallString<128> CfgFileName(FileName);
668 llvm::sys::path::native(CfgFileName);
669 ConfigFile = CfgFileName.str();
670 bool ContainErrors;
671 CfgOptions = llvm::make_unique<InputArgList>(
672 ParseArgStrings(NewCfgArgs, ContainErrors));
673 if (ContainErrors) {
674 CfgOptions.reset();
675 return true;
676 }
677
678 if (CfgOptions->hasArg(options::OPT_config)) {
679 CfgOptions.reset();
680 Diag(diag::err_drv_nested_config_file);
681 return true;
682 }
683
684 // Claim all arguments that come from a configuration file so that the driver
685 // does not warn on any that is unused.
686 for (Arg *A : *CfgOptions)
687 A->claim();
688 return false;
689}
690
691bool Driver::loadConfigFile() {
692 std::string CfgFileName;
693 bool FileSpecifiedExplicitly = false;
694
695 // Process options that change search path for config files.
696 if (CLOptions) {
697 if (CLOptions->hasArg(options::OPT_config_system_dir_EQ)) {
698 SmallString<128> CfgDir;
699 CfgDir.append(
700 CLOptions->getLastArgValue(options::OPT_config_system_dir_EQ));
701 if (!CfgDir.empty()) {
Sam McCall296d8322018-01-02 09:35:10 +0000702 if (llvm::sys::fs::make_absolute(CfgDir).value() != 0)
Serge Pavlov208ac652018-01-01 13:27:01 +0000703 SystemConfigDir.clear();
704 else
705 SystemConfigDir = std::string(CfgDir.begin(), CfgDir.end());
706 }
707 }
708 if (CLOptions->hasArg(options::OPT_config_user_dir_EQ)) {
709 SmallString<128> CfgDir;
710 CfgDir.append(
711 CLOptions->getLastArgValue(options::OPT_config_user_dir_EQ));
712 if (!CfgDir.empty()) {
Sam McCall296d8322018-01-02 09:35:10 +0000713 if (llvm::sys::fs::make_absolute(CfgDir).value() != 0)
Serge Pavlov208ac652018-01-01 13:27:01 +0000714 UserConfigDir.clear();
715 else
716 UserConfigDir = std::string(CfgDir.begin(), CfgDir.end());
717 }
718 }
719 }
720
721 // First try to find config file specified in command line.
722 if (CLOptions) {
723 std::vector<std::string> ConfigFiles =
724 CLOptions->getAllArgValues(options::OPT_config);
725 if (ConfigFiles.size() > 1) {
726 Diag(diag::err_drv_duplicate_config);
727 return true;
728 }
729
730 if (!ConfigFiles.empty()) {
731 CfgFileName = ConfigFiles.front();
732 assert(!CfgFileName.empty());
733
734 // If argument contains directory separator, treat it as a path to
735 // configuration file.
736 if (llvm::sys::path::has_parent_path(CfgFileName)) {
737 SmallString<128> CfgFilePath;
738 if (llvm::sys::path::is_relative(CfgFileName))
739 llvm::sys::fs::current_path(CfgFilePath);
740 llvm::sys::path::append(CfgFilePath, CfgFileName);
741 if (!llvm::sys::fs::is_regular_file(CfgFilePath)) {
742 Diag(diag::err_drv_config_file_not_exist) << CfgFilePath;
743 return true;
744 }
745 return readConfigFile(CfgFilePath);
746 }
747
748 FileSpecifiedExplicitly = true;
749 }
750 }
751
752 // If config file is not specified explicitly, try to deduce configuration
753 // from executable name. For instance, an executable 'armv7l-clang' will
754 // search for config file 'armv7l-clang.cfg'.
755 if (CfgFileName.empty() && !ClangNameParts.TargetPrefix.empty())
756 CfgFileName = ClangNameParts.TargetPrefix + '-' + ClangNameParts.ModeSuffix;
757
758 if (CfgFileName.empty())
759 return false;
760
761 // Determine architecture part of the file name, if it is present.
762 StringRef CfgFileArch = CfgFileName;
763 size_t ArchPrefixLen = CfgFileArch.find('-');
764 if (ArchPrefixLen == StringRef::npos)
765 ArchPrefixLen = CfgFileArch.size();
766 llvm::Triple CfgTriple;
767 CfgFileArch = CfgFileArch.take_front(ArchPrefixLen);
768 CfgTriple = llvm::Triple(llvm::Triple::normalize(CfgFileArch));
769 if (CfgTriple.getArch() == llvm::Triple::ArchType::UnknownArch)
770 ArchPrefixLen = 0;
771
772 if (!StringRef(CfgFileName).endswith(".cfg"))
773 CfgFileName += ".cfg";
774
775 // If config file starts with architecture name and command line options
776 // redefine architecture (with options like -m32 -LE etc), try finding new
777 // config file with that architecture.
778 SmallString<128> FixedConfigFile;
779 size_t FixedArchPrefixLen = 0;
780 if (ArchPrefixLen) {
781 // Get architecture name from config file name like 'i386.cfg' or
782 // 'armv7l-clang.cfg'.
783 // Check if command line options changes effective triple.
784 llvm::Triple EffectiveTriple = computeTargetTriple(*this,
785 CfgTriple.getTriple(), *CLOptions);
786 if (CfgTriple.getArch() != EffectiveTriple.getArch()) {
787 FixedConfigFile = EffectiveTriple.getArchName();
788 FixedArchPrefixLen = FixedConfigFile.size();
789 // Append the rest of original file name so that file name transforms
790 // like: i386-clang.cfg -> x86_64-clang.cfg.
791 if (ArchPrefixLen < CfgFileName.size())
792 FixedConfigFile += CfgFileName.substr(ArchPrefixLen);
793 }
794 }
795
796 // Prepare list of directories where config file is searched for.
797 SmallVector<std::string, 3> CfgFileSearchDirs;
798 CfgFileSearchDirs.push_back(UserConfigDir);
799 CfgFileSearchDirs.push_back(SystemConfigDir);
800 CfgFileSearchDirs.push_back(Dir);
801
802 // Try to find config file. First try file with corrected architecture.
803 llvm::SmallString<128> CfgFilePath;
804 if (!FixedConfigFile.empty()) {
805 if (searchForFile(CfgFilePath, CfgFileSearchDirs, FixedConfigFile))
806 return readConfigFile(CfgFilePath);
807 // If 'x86_64-clang.cfg' was not found, try 'x86_64.cfg'.
808 FixedConfigFile.resize(FixedArchPrefixLen);
809 FixedConfigFile.append(".cfg");
810 if (searchForFile(CfgFilePath, CfgFileSearchDirs, FixedConfigFile))
811 return readConfigFile(CfgFilePath);
812 }
813
814 // Then try original file name.
815 if (searchForFile(CfgFilePath, CfgFileSearchDirs, CfgFileName))
816 return readConfigFile(CfgFilePath);
817
818 // Finally try removing driver mode part: 'x86_64-clang.cfg' -> 'x86_64.cfg'.
819 if (!ClangNameParts.ModeSuffix.empty() &&
820 !ClangNameParts.TargetPrefix.empty()) {
821 CfgFileName.assign(ClangNameParts.TargetPrefix);
822 CfgFileName.append(".cfg");
823 if (searchForFile(CfgFilePath, CfgFileSearchDirs, CfgFileName))
824 return readConfigFile(CfgFilePath);
825 }
826
827 // Report error but only if config file was specified explicitly, by option
828 // --config. If it was deduced from executable name, it is not an error.
829 if (FileSpecifiedExplicitly) {
830 Diag(diag::err_drv_config_file_not_found) << CfgFileName;
831 for (const std::string &SearchDir : CfgFileSearchDirs)
832 if (!SearchDir.empty())
833 Diag(diag::note_drv_config_file_searched_in) << SearchDir;
834 return true;
835 }
836
837 return false;
838}
839
Chris Lattner54b16772011-07-23 17:14:25 +0000840Compilation *Driver::BuildCompilation(ArrayRef<const char *> ArgList) {
Daniel Dunbar2608c542009-03-18 01:38:48 +0000841 llvm::PrettyStackTraceString CrashInfo("Compilation construction");
842
Eric Christopherf901e852011-08-17 22:59:59 +0000843 // FIXME: Handle environment options which affect driver behavior, somewhere
Bill Wendlingadbeb9f2012-03-12 21:24:57 +0000844 // (client?). GCC_EXEC_PREFIX, LPATH, CC_PRINT_OPTIONS.
Chad Rosier82301162011-09-14 00:47:55 +0000845
David Majnemer85c25b42016-07-24 17:44:03 +0000846 if (Optional<std::string> CompilerPathValue =
847 llvm::sys::Process::GetEnv("COMPILER_PATH")) {
848 StringRef CompilerPath = *CompilerPathValue;
Chad Rosier82301162011-09-14 00:47:55 +0000849 while (!CompilerPath.empty()) {
Douglas Katzmana67e50c2015-06-26 15:47:46 +0000850 std::pair<StringRef, StringRef> Split =
851 CompilerPath.split(llvm::sys::EnvPathSeparator);
Chad Rosier82301162011-09-14 00:47:55 +0000852 PrefixDirs.push_back(Split.first);
853 CompilerPath = Split.second;
854 }
855 }
Daniel Dunbar5e0f6af2009-03-13 00:51:18 +0000856
Hans Wennborg70850d82013-07-18 20:29:38 +0000857 // We look for the driver mode option early, because the mode can affect
858 // how other options are parsed.
Zachary Turneraff19c32016-08-12 17:47:52 +0000859 ParseDriverMode(ClangExecutable, ArgList.slice(1));
Hans Wennborg70850d82013-07-18 20:29:38 +0000860
Daniel Dunbar5e0f6af2009-03-13 00:51:18 +0000861 // FIXME: What are we going to do with -V and -b?
862
Serge Pavlov208ac652018-01-01 13:27:01 +0000863 // Arguments specified in command line.
864 bool ContainsError;
865 CLOptions = llvm::make_unique<InputArgList>(
866 ParseArgStrings(ArgList.slice(1), ContainsError));
867
868 // Try parsing configuration file.
869 if (!ContainsError)
870 ContainsError = loadConfigFile();
871 bool HasConfigFile = !ContainsError && (CfgOptions.get() != nullptr);
872
873 // All arguments, from both config file and command line.
874 InputArgList Args = std::move(HasConfigFile ? std::move(*CfgOptions)
875 : std::move(*CLOptions));
876 if (HasConfigFile)
877 for (auto *Opt : *CLOptions) {
878 const Arg *BaseArg = &Opt->getBaseArg();
879 if (BaseArg == Opt)
880 BaseArg = nullptr;
881 Arg *Copy = new llvm::opt::Arg(Opt->getOption(), Opt->getSpelling(),
882 Args.size(), BaseArg);
883 Copy->getValues() = Opt->getValues();
884 if (Opt->isClaimed())
885 Copy->claim();
886 Args.append(Copy);
887 }
888
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +0000889 // FIXME: This stuff needs to go into the Compilation, not the driver.
Douglas Katzmanb7e8ef02015-06-25 19:37:41 +0000890 bool CCCPrintPhases;
Daniel Dunbard02cb1d2009-03-05 06:38:47 +0000891
Filipe Cabecinhas136f35e2015-07-18 06:35:24 +0000892 // Silence driver warnings if requested
893 Diags.setIgnoreAllWarnings(Args.hasArg(options::OPT_w));
894
Rafael Espindola59ae7992009-12-07 18:28:29 +0000895 // -no-canonical-prefixes is used very early in main.
David Blaikie69a1d8c2015-06-22 22:07:27 +0000896 Args.ClaimAllArgs(options::OPT_no_canonical_prefixes);
Rafael Espindola59ae7992009-12-07 18:28:29 +0000897
Daniel Dunbar926f81f2010-08-02 02:38:03 +0000898 // Ignore -pipe.
David Blaikie69a1d8c2015-06-22 22:07:27 +0000899 Args.ClaimAllArgs(options::OPT_pipe);
Daniel Dunbar926f81f2010-08-02 02:38:03 +0000900
Daniel Dunbaracd69572009-12-04 21:55:23 +0000901 // Extract -ccc args.
Daniel Dunbaree66cf22009-03-10 20:52:46 +0000902 //
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +0000903 // FIXME: We need to figure out where this behavior should live. Most of it
904 // should be outside in the client; the parts that aren't should have proper
905 // options, either by introducing new ones or by overloading gcc ones like -V
906 // or -b.
Douglas Katzmanb7e8ef02015-06-25 19:37:41 +0000907 CCCPrintPhases = Args.hasArg(options::OPT_ccc_print_phases);
David Blaikie69a1d8c2015-06-22 22:07:27 +0000908 CCCPrintBindings = Args.hasArg(options::OPT_ccc_print_bindings);
909 if (const Arg *A = Args.getLastArg(options::OPT_ccc_gcc_name))
Richard Smithbd55daf2012-11-01 04:30:05 +0000910 CCCGenericGCCName = A->getValue();
David Blaikie69a1d8c2015-06-22 22:07:27 +0000911 CCCUsePCH =
912 Args.hasFlag(options::OPT_ccc_pch_is_pch, options::OPT_ccc_pch_is_pth);
Bruno Cardoso Lopes52dfe712017-04-12 21:46:20 +0000913 GenReproducer = Args.hasFlag(options::OPT_gen_reproducer,
914 options::OPT_fno_crash_diagnostics,
915 !!::getenv("FORCE_CLANG_DIAGNOSTICS_CRASH"));
Joerg Sonnenberger17d75512012-02-22 19:15:16 +0000916 // FIXME: DefaultTargetTriple is used by the target-prefixed calls to as/ld
917 // and getToolChain is const.
Hans Wennborg2e274592013-08-13 23:38:57 +0000918 if (IsCLMode()) {
Hans Wennborg73609a02014-03-28 01:19:04 +0000919 // clang-cl targets MSVC-style Win32.
Hans Wennborg2e274592013-08-13 23:38:57 +0000920 llvm::Triple T(DefaultTargetTriple);
Hans Wennborg9d9ce7a2014-03-28 20:49:28 +0000921 T.setOS(llvm::Triple::Win32);
Hans Wennborg0f0e8d62015-09-18 17:11:50 +0000922 T.setVendor(llvm::Triple::PC);
Hans Wennborg9d9ce7a2014-03-28 20:49:28 +0000923 T.setEnvironment(llvm::Triple::MSVC);
Oleg Ranevskyy80523182017-08-31 20:31:30 +0000924 T.setObjectFormat(llvm::Triple::COFF);
Hans Wennborg2e274592013-08-13 23:38:57 +0000925 DefaultTargetTriple = T.str();
926 }
David Blaikie69a1d8c2015-06-22 22:07:27 +0000927 if (const Arg *A = Args.getLastArg(options::OPT_target))
Richard Smithbd55daf2012-11-01 04:30:05 +0000928 DefaultTargetTriple = A->getValue();
David Blaikie69a1d8c2015-06-22 22:07:27 +0000929 if (const Arg *A = Args.getLastArg(options::OPT_ccc_install_dir))
Richard Smithbd55daf2012-11-01 04:30:05 +0000930 Dir = InstalledDir = A->getValue();
David Blaikie69a1d8c2015-06-22 22:07:27 +0000931 for (const Arg *A : Args.filtered(options::OPT_B)) {
Benjamin Kramer1a648d12011-02-08 20:31:42 +0000932 A->claim();
Richard Smithbd55daf2012-11-01 04:30:05 +0000933 PrefixDirs.push_back(A->getValue(0));
Benjamin Kramer1a648d12011-02-08 20:31:42 +0000934 }
David Blaikie69a1d8c2015-06-22 22:07:27 +0000935 if (const Arg *A = Args.getLastArg(options::OPT__sysroot_EQ))
Richard Smithbd55daf2012-11-01 04:30:05 +0000936 SysRoot = A->getValue();
David Blaikie69a1d8c2015-06-22 22:07:27 +0000937 if (const Arg *A = Args.getLastArg(options::OPT__dyld_prefix_EQ))
Peter Collingbourne9d9e1fc2013-05-27 21:40:20 +0000938 DyldPrefix = A->getValue();
Daniel Dunbaree66cf22009-03-10 20:52:46 +0000939
David Blaikie69a1d8c2015-06-22 22:07:27 +0000940 if (const Arg *A = Args.getLastArg(options::OPT_resource_dir))
Bob Wilsona20a1da2013-03-23 05:17:59 +0000941 ResourceDir = A->getValue();
Jim Grosbach061dabf2013-03-12 20:17:58 +0000942
David Blaikie69a1d8c2015-06-22 22:07:27 +0000943 if (const Arg *A = Args.getLastArg(options::OPT_save_temps_EQ)) {
Reid Kleckner68eb60b2015-02-02 22:41:48 +0000944 SaveTemps = llvm::StringSwitch<SaveTempsMode>(A->getValue())
945 .Case("cwd", SaveTempsCwd)
946 .Case("obj", SaveTempsObj)
947 .Default(SaveTempsCwd);
948 }
949
Steven Wu1257cd82016-05-18 17:04:52 +0000950 setLTOMode(Args);
951
Steven Wu844ab6a2016-11-16 06:06:44 +0000952 // Process -fembed-bitcode= flags.
953 if (Arg *A = Args.getLastArg(options::OPT_fembed_bitcode_EQ)) {
954 StringRef Name = A->getValue();
955 unsigned Model = llvm::StringSwitch<unsigned>(Name)
956 .Case("off", EmbedNone)
957 .Case("all", EmbedBitcode)
958 .Case("bitcode", EmbedBitcode)
959 .Case("marker", EmbedMarker)
960 .Default(~0U);
961 if (Model == ~0U) {
962 Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args)
963 << Name;
964 } else
965 BitcodeEmbed = static_cast<BitcodeEmbedMode>(Model);
Steven Wu574b0f22016-03-01 01:07:58 +0000966 }
967
David Blaikie69a1d8c2015-06-22 22:07:27 +0000968 std::unique_ptr<llvm::opt::InputArgList> UArgs =
969 llvm::make_unique<InputArgList>(std::move(Args));
970
Daniel Dunbar775d4062010-06-11 22:00:26 +0000971 // Perform the default argument translations.
David Blaikie69a1d8c2015-06-22 22:07:27 +0000972 DerivedArgList *TranslatedArgs = TranslateInputArgs(*UArgs);
Daniel Dunbar775d4062010-06-11 22:00:26 +0000973
Chandler Carruthcb916192012-01-25 08:49:21 +0000974 // Owned by the host.
Andrey Turetskiy6a8b91d2016-04-21 10:16:48 +0000975 const ToolChain &TC = getToolChain(
976 *UArgs, computeTargetTriple(*this, DefaultTargetTriple, *UArgs));
Chandler Carruthcb916192012-01-25 08:49:21 +0000977
Daniel Dunbar3ce436d2009-03-16 06:42:30 +0000978 // The compilation takes ownership of Args.
Benjamin Kramer43c0f482017-06-30 13:21:27 +0000979 Compilation *C = new Compilation(*this, TC, UArgs.release(), TranslatedArgs,
980 ContainsError);
Daniel Dunbarf0eddb82009-03-18 02:55:38 +0000981
Daniel Dunbarf0eddb82009-03-18 02:55:38 +0000982 if (!HandleImmediateArgs(*C))
983 return C;
984
Chad Rosierecdede82011-08-12 22:08:57 +0000985 // Construct the list of inputs.
986 InputList Inputs;
Hans Wennborged1d0722013-08-13 21:32:29 +0000987 BuildInputs(C->getDefaultToolChain(), *TranslatedArgs, Inputs);
Chad Rosierecdede82011-08-12 22:08:57 +0000988
Samuel Antaoc1ffba52016-06-13 18:10:57 +0000989 // Populate the tool chains for the offloading devices, if any.
990 CreateOffloadingDeviceToolChains(*C, Inputs);
Justin Lebar0e450a52016-03-30 23:30:25 +0000991
Chandler Carruth7f1417f2012-01-24 10:43:44 +0000992 // Construct the list of abstract actions to perform for this compilation. On
Tim Northover157d9112014-01-16 08:48:16 +0000993 // MachO targets this uses the driver-driver and universal actions.
994 if (TC.getTriple().isOSBinFormatMachO())
Artem Belevich5e2a3ec2015-11-17 22:28:40 +0000995 BuildUniversalActions(*C, C->getDefaultToolChain(), Inputs);
Daniel Dunbarf0eddb82009-03-18 02:55:38 +0000996 else
Justin Lebar0f3474c2016-02-11 02:00:50 +0000997 BuildActions(*C, C->getArgs(), Inputs, C->getActions());
Daniel Dunbarf0eddb82009-03-18 02:55:38 +0000998
Douglas Katzmanb7e8ef02015-06-25 19:37:41 +0000999 if (CCCPrintPhases) {
Daniel Dunbareb843be2009-03-18 03:13:20 +00001000 PrintActions(*C);
Daniel Dunbarf0eddb82009-03-18 02:55:38 +00001001 return C;
1002 }
1003
1004 BuildJobs(*C);
Daniel Dunbaradc91e62009-03-15 01:38:15 +00001005
1006 return C;
Daniel Dunbaree66cf22009-03-10 20:52:46 +00001007}
1008
Justin Bognered9cbe02015-07-09 06:58:31 +00001009static void printArgList(raw_ostream &OS, const llvm::opt::ArgList &Args) {
1010 llvm::opt::ArgStringList ASL;
1011 for (const auto *A : Args)
1012 A->render(Args, ASL);
1013
1014 for (auto I = ASL.begin(), E = ASL.end(); I != E; ++I) {
1015 if (I != ASL.begin())
1016 OS << ' ';
1017 Command::printArg(OS, *I, true);
1018 }
1019 OS << '\n';
1020}
1021
Bruno Cardoso Lopes02681c42016-11-17 21:41:22 +00001022bool Driver::getCrashDiagnosticFile(StringRef ReproCrashFilename,
1023 SmallString<128> &CrashDiagDir) {
1024 using namespace llvm::sys;
1025 assert(llvm::Triple(llvm::sys::getProcessTriple()).isOSDarwin() &&
1026 "Only knows about .crash files on Darwin");
1027
1028 // The .crash file can be found on at ~/Library/Logs/DiagnosticReports/
1029 // (or /Library/Logs/DiagnosticReports for root) and has the filename pattern
1030 // clang-<VERSION>_<YYYY-MM-DD-HHMMSS>_<hostname>.crash.
1031 path::home_directory(CrashDiagDir);
1032 if (CrashDiagDir.startswith("/var/root"))
1033 CrashDiagDir = "/";
1034 path::append(CrashDiagDir, "Library/Logs/DiagnosticReports");
1035 int PID =
1036#if LLVM_ON_UNIX
1037 getpid();
1038#else
1039 0;
1040#endif
1041 std::error_code EC;
1042 fs::file_status FileStatus;
1043 TimePoint<> LastAccessTime;
1044 SmallString<128> CrashFilePath;
1045 // Lookup the .crash files and get the one generated by a subprocess spawned
1046 // by this driver invocation.
1047 for (fs::directory_iterator File(CrashDiagDir, EC), FileEnd;
1048 File != FileEnd && !EC; File.increment(EC)) {
1049 StringRef FileName = path::filename(File->path());
1050 if (!FileName.startswith(Name))
1051 continue;
1052 if (fs::status(File->path(), FileStatus))
1053 continue;
1054 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> CrashFile =
1055 llvm::MemoryBuffer::getFile(File->path());
1056 if (!CrashFile)
1057 continue;
1058 // The first line should start with "Process:", otherwise this isn't a real
1059 // .crash file.
1060 StringRef Data = CrashFile.get()->getBuffer();
1061 if (!Data.startswith("Process:"))
1062 continue;
1063 // Parse parent process pid line, e.g: "Parent Process: clang-4.0 [79141]"
1064 size_t ParentProcPos = Data.find("Parent Process:");
1065 if (ParentProcPos == StringRef::npos)
1066 continue;
1067 size_t LineEnd = Data.find_first_of("\n", ParentProcPos);
1068 if (LineEnd == StringRef::npos)
1069 continue;
1070 StringRef ParentProcess = Data.slice(ParentProcPos+15, LineEnd).trim();
1071 int OpenBracket = -1, CloseBracket = -1;
1072 for (size_t i = 0, e = ParentProcess.size(); i < e; ++i) {
1073 if (ParentProcess[i] == '[')
1074 OpenBracket = i;
1075 if (ParentProcess[i] == ']')
1076 CloseBracket = i;
1077 }
1078 // Extract the parent process PID from the .crash file and check whether
1079 // it matches this driver invocation pid.
1080 int CrashPID;
1081 if (OpenBracket < 0 || CloseBracket < 0 ||
1082 ParentProcess.slice(OpenBracket + 1, CloseBracket)
1083 .getAsInteger(10, CrashPID) || CrashPID != PID) {
1084 continue;
1085 }
1086
1087 // Found a .crash file matching the driver pid. To avoid getting an older
1088 // and misleading crash file, continue looking for the most recent.
1089 // FIXME: the driver can dispatch multiple cc1 invocations, leading to
1090 // multiple crashes poiting to the same parent process. Since the driver
1091 // does not collect pid information for the dispatched invocation there's
1092 // currently no way to distinguish among them.
1093 const auto FileAccessTime = FileStatus.getLastModificationTime();
1094 if (FileAccessTime > LastAccessTime) {
1095 CrashFilePath.assign(File->path());
1096 LastAccessTime = FileAccessTime;
1097 }
1098 }
1099
1100 // If found, copy it over to the location of other reproducer files.
1101 if (!CrashFilePath.empty()) {
1102 EC = fs::copy_file(CrashFilePath, ReproCrashFilename);
1103 if (EC)
1104 return false;
1105 return true;
1106 }
1107
1108 return false;
1109}
1110
Eric Christopherf901e852011-08-17 22:59:59 +00001111// When clang crashes, produce diagnostic information including the fully
1112// preprocessed source file(s). Request that the developer attach the
Chad Rosierbe10f982011-08-02 17:58:04 +00001113// diagnostic information to a bug report.
1114void Driver::generateCompilationDiagnostics(Compilation &C,
Justin Bognere1a33d12014-10-20 21:02:05 +00001115 const Command &FailingCommand) {
Chad Rosier877c0a22012-02-22 00:30:39 +00001116 if (C.getArgs().hasArg(options::OPT_fno_crash_diagnostics))
Chad Rosier62135492012-07-09 17:31:28 +00001117 return;
Chad Rosierbee5a1d2012-03-07 00:30:40 +00001118
Chad Rosierdbf46a12013-02-01 18:30:26 +00001119 // Don't try to generate diagnostics for link or dsymutil jobs.
Justin Bognere1a33d12014-10-20 21:02:05 +00001120 if (FailingCommand.getCreator().isLinkJob() ||
1121 FailingCommand.getCreator().isDsymutilJob())
Chad Rosier877c0a22012-02-22 00:30:39 +00001122 return;
1123
Chad Rosier8179f112012-06-19 17:51:34 +00001124 // Print the version of the compiler.
1125 PrintVersion(C, llvm::errs());
1126
Chad Rosierbe10f982011-08-02 17:58:04 +00001127 Diag(clang::diag::note_drv_command_failed_diag_msg)
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001128 << "PLEASE submit a bug report to " BUG_REPORT_URL " and include the "
1129 "crash backtrace, preprocessed source, and associated run script.";
Chad Rosierbe10f982011-08-02 17:58:04 +00001130
1131 // Suppress driver output and emit preprocessor output to temp file.
Hans Wennborg70850d82013-07-18 20:29:38 +00001132 Mode = CPPMode;
Chad Rosierbe10f982011-08-02 17:58:04 +00001133 CCGenDiagnostics = true;
1134
Chad Rosiercdb008d2011-11-02 21:29:05 +00001135 // Save the original job command(s).
Justin Bogner25645152014-10-21 17:24:44 +00001136 Command Cmd = FailingCommand;
Chad Rosiercdb008d2011-11-02 21:29:05 +00001137
Richard Smith5bb4cdf2012-12-20 02:22:15 +00001138 // Keep track of whether we produce any errors while trying to produce
1139 // preprocessed sources.
1140 DiagnosticErrorTrap Trap(Diags);
1141
1142 // Suppress tool output.
Chad Rosierbe10f982011-08-02 17:58:04 +00001143 C.initCompilationForDiagnostics();
Chad Rosierecdede82011-08-12 22:08:57 +00001144
1145 // Construct the list of inputs.
1146 InputList Inputs;
1147 BuildInputs(C.getDefaultToolChain(), C.getArgs(), Inputs);
Chad Rosierbe10f982011-08-02 17:58:04 +00001148
Chad Rosier4f81fc22011-08-12 23:30:05 +00001149 for (InputList::iterator it = Inputs.begin(), ie = Inputs.end(); it != ie;) {
Chad Rosierd57133d2011-08-18 00:22:25 +00001150 bool IgnoreInput = false;
1151
1152 // Ignore input from stdin or any inputs that cannot be preprocessed.
Paul Robinsonf44157d2014-04-28 22:24:44 +00001153 // Check type first as not all linker inputs have a value.
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001154 if (types::getPreprocessedType(it->first) == types::TY_INVALID) {
Paul Robinsonf44157d2014-04-28 22:24:44 +00001155 IgnoreInput = true;
1156 } else if (!strcmp(it->second->getValue(), "-")) {
Chad Rosierd57133d2011-08-18 00:22:25 +00001157 Diag(clang::diag::note_drv_command_failed_diag_msg)
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001158 << "Error generating preprocessed source(s) - "
1159 "ignoring input from stdin.";
Chad Rosierd57133d2011-08-18 00:22:25 +00001160 IgnoreInput = true;
Chad Rosierd57133d2011-08-18 00:22:25 +00001161 }
1162
1163 if (IgnoreInput) {
Chad Rosier4f81fc22011-08-12 23:30:05 +00001164 it = Inputs.erase(it);
1165 ie = Inputs.end();
Chad Rosier6fdf38b2011-08-17 23:08:45 +00001166 } else {
Chad Rosier4f81fc22011-08-12 23:30:05 +00001167 ++it;
Chad Rosier6fdf38b2011-08-17 23:08:45 +00001168 }
Chad Rosier4f81fc22011-08-12 23:30:05 +00001169 }
Chad Rosierd57133d2011-08-18 00:22:25 +00001170
Chad Rosierc5103c32013-01-29 23:57:10 +00001171 if (Inputs.empty()) {
1172 Diag(clang::diag::note_drv_command_failed_diag_msg)
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001173 << "Error generating preprocessed source(s) - "
1174 "no preprocessable inputs.";
Chad Rosierc5103c32013-01-29 23:57:10 +00001175 return;
1176 }
1177
Chad Rosiere75ef402011-09-06 23:52:36 +00001178 // Don't attempt to generate preprocessed files if multiple -arch options are
Chad Rosier636d2832012-02-13 18:16:28 +00001179 // used, unless they're all duplicates.
1180 llvm::StringSet<> ArchNames;
Saleem Abdulrasool688b6bc2014-12-29 19:01:36 +00001181 for (const Arg *A : C.getArgs()) {
Chad Rosiere75ef402011-09-06 23:52:36 +00001182 if (A->getOption().matches(options::OPT_arch)) {
Richard Smithbd55daf2012-11-01 04:30:05 +00001183 StringRef ArchName = A->getValue();
Chad Rosier636d2832012-02-13 18:16:28 +00001184 ArchNames.insert(ArchName);
Chad Rosiere75ef402011-09-06 23:52:36 +00001185 }
1186 }
Chad Rosier636d2832012-02-13 18:16:28 +00001187 if (ArchNames.size() > 1) {
1188 Diag(clang::diag::note_drv_command_failed_diag_msg)
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001189 << "Error generating preprocessed source(s) - cannot generate "
1190 "preprocessed source with multiple -arch options.";
Chad Rosier636d2832012-02-13 18:16:28 +00001191 return;
1192 }
Chad Rosiere75ef402011-09-06 23:52:36 +00001193
Chandler Carruth7f1417f2012-01-24 10:43:44 +00001194 // Construct the list of abstract actions to perform for this compilation. On
1195 // Darwin OSes this uses the driver-driver and builds universal actions.
Chandler Carruthcb916192012-01-25 08:49:21 +00001196 const ToolChain &TC = C.getDefaultToolChain();
Tim Northover157d9112014-01-16 08:48:16 +00001197 if (TC.getTriple().isOSBinFormatMachO())
Artem Belevich5e2a3ec2015-11-17 22:28:40 +00001198 BuildUniversalActions(C, TC, Inputs);
Chad Rosierbe10f982011-08-02 17:58:04 +00001199 else
Justin Lebar0f3474c2016-02-11 02:00:50 +00001200 BuildActions(C, C.getArgs(), Inputs, C.getActions());
Chad Rosierbe10f982011-08-02 17:58:04 +00001201
1202 BuildJobs(C);
1203
1204 // If there were errors building the compilation, quit now.
Richard Smith5bb4cdf2012-12-20 02:22:15 +00001205 if (Trap.hasErrorOccurred()) {
Chad Rosierbe10f982011-08-02 17:58:04 +00001206 Diag(clang::diag::note_drv_command_failed_diag_msg)
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001207 << "Error generating preprocessed source(s).";
Chad Rosierbe10f982011-08-02 17:58:04 +00001208 return;
1209 }
1210
1211 // Generate preprocessed output.
Chad Rosierdd60e092013-01-29 20:15:05 +00001212 SmallVector<std::pair<int, const Command *>, 4> FailingCommands;
Justin Bogner0cd92482015-07-02 22:52:08 +00001213 C.ExecuteJobs(C.getJobs(), FailingCommands);
Chad Rosierbe10f982011-08-02 17:58:04 +00001214
Justin Bognerbc89b182014-10-20 21:20:27 +00001215 // If any of the preprocessing commands failed, clean up and exit.
1216 if (!FailingCommands.empty()) {
Reid Kleckner68eb60b2015-02-02 22:41:48 +00001217 if (!isSaveTempsEnabled())
Chad Rosierbe10f982011-08-02 17:58:04 +00001218 C.CleanupFileList(C.getTempFiles(), true);
1219
1220 Diag(clang::diag::note_drv_command_failed_diag_msg)
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001221 << "Error generating preprocessed source(s).";
Justin Bognerbc89b182014-10-20 21:20:27 +00001222 return;
Chad Rosierbe10f982011-08-02 17:58:04 +00001223 }
Justin Bognerbc89b182014-10-20 21:20:27 +00001224
Justin Bognerc1fdf7f2014-10-20 21:47:56 +00001225 const ArgStringList &TempFiles = C.getTempFiles();
1226 if (TempFiles.empty()) {
1227 Diag(clang::diag::note_drv_command_failed_diag_msg)
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001228 << "Error generating preprocessed source(s).";
Justin Bognerc1fdf7f2014-10-20 21:47:56 +00001229 return;
1230 }
1231
Justin Bognerbc89b182014-10-20 21:20:27 +00001232 Diag(clang::diag::note_drv_command_failed_diag_msg)
1233 << "\n********************\n\n"
1234 "PLEASE ATTACH THE FOLLOWING FILES TO THE BUG REPORT:\n"
1235 "Preprocessed source(s) and associated run script(s) are located at:";
Justin Bognerbc89b182014-10-20 21:20:27 +00001236
Justin Bogner659ecc32014-10-20 22:47:23 +00001237 SmallString<128> VFS;
Bruno Cardoso Lopes02681c42016-11-17 21:41:22 +00001238 SmallString<128> ReproCrashFilename;
Justin Bogner659ecc32014-10-20 22:47:23 +00001239 for (const char *TempFile : TempFiles) {
Justin Bognerc1fdf7f2014-10-20 21:47:56 +00001240 Diag(clang::diag::note_drv_command_failed_diag_msg) << TempFile;
Bruno Cardoso Lopes02681c42016-11-17 21:41:22 +00001241 if (ReproCrashFilename.empty()) {
1242 ReproCrashFilename = TempFile;
1243 llvm::sys::path::replace_extension(ReproCrashFilename, ".crash");
1244 }
Justin Bogner659ecc32014-10-20 22:47:23 +00001245 if (StringRef(TempFile).endswith(".cache")) {
1246 // In some cases (modules) we'll dump extra data to help with reproducing
1247 // the crash into a directory next to the output.
1248 VFS = llvm::sys::path::filename(TempFile);
1249 llvm::sys::path::append(VFS, "vfs", "vfs.yaml");
1250 }
1251 }
Justin Bognerc1fdf7f2014-10-20 21:47:56 +00001252
1253 // Assume associated files are based off of the first temporary file.
Justin Bogner25645152014-10-21 17:24:44 +00001254 CrashReportInfo CrashInfo(TempFiles[0], VFS);
Justin Bognerc1fdf7f2014-10-20 21:47:56 +00001255
Justin Bogner25645152014-10-21 17:24:44 +00001256 std::string Script = CrashInfo.Filename.rsplit('.').first.str() + ".sh";
Justin Bognerc1fdf7f2014-10-20 21:47:56 +00001257 std::error_code EC;
Justin Bognerc1fdf7f2014-10-20 21:47:56 +00001258 llvm::raw_fd_ostream ScriptOS(Script, EC, llvm::sys::fs::F_Excl);
1259 if (EC) {
1260 Diag(clang::diag::note_drv_command_failed_diag_msg)
1261 << "Error generating run script: " + Script + " " + EC.message();
1262 } else {
Justin Bogner42220ed2015-03-12 00:14:35 +00001263 ScriptOS << "# Crash reproducer for " << getClangFullVersion() << "\n"
Justin Bognered9cbe02015-07-09 06:58:31 +00001264 << "# Driver args: ";
1265 printArgList(ScriptOS, C.getInputArgs());
1266 ScriptOS << "# Original command: ";
Justin Bogner42220ed2015-03-12 00:14:35 +00001267 Cmd.Print(ScriptOS, "\n", /*Quote=*/true);
Justin Bogner33bdbc62014-10-21 18:03:08 +00001268 Cmd.Print(ScriptOS, "\n", /*Quote=*/true, &CrashInfo);
Justin Bognerc1fdf7f2014-10-20 21:47:56 +00001269 Diag(clang::diag::note_drv_command_failed_diag_msg) << Script;
Justin Bognerbc89b182014-10-20 21:20:27 +00001270 }
Saleem Abdulrasool3661a822015-01-12 02:33:09 +00001271
Bruno Cardoso Lopes02681c42016-11-17 21:41:22 +00001272 // On darwin, provide information about the .crash diagnostic report.
1273 if (llvm::Triple(llvm::sys::getProcessTriple()).isOSDarwin()) {
1274 SmallString<128> CrashDiagDir;
1275 if (getCrashDiagnosticFile(ReproCrashFilename, CrashDiagDir)) {
1276 Diag(clang::diag::note_drv_command_failed_diag_msg)
1277 << ReproCrashFilename.str();
1278 } else { // Suggest a directory for the user to look for .crash files.
1279 llvm::sys::path::append(CrashDiagDir, Name);
1280 CrashDiagDir += "_<YYYY-MM-DD-HHMMSS>_<hostname>.crash";
1281 Diag(clang::diag::note_drv_command_failed_diag_msg)
1282 << "Crash backtrace is located in";
1283 Diag(clang::diag::note_drv_command_failed_diag_msg)
1284 << CrashDiagDir.str();
1285 Diag(clang::diag::note_drv_command_failed_diag_msg)
1286 << "(choose the .crash file that corresponds to your crash)";
1287 }
1288 }
1289
Saleem Abdulrasool3661a822015-01-12 02:33:09 +00001290 for (const auto &A : C.getArgs().filtered(options::OPT_frewrite_map_file,
1291 options::OPT_frewrite_map_file_EQ))
1292 Diag(clang::diag::note_drv_command_failed_diag_msg) << A->getValue();
1293
Justin Bognerbc89b182014-10-20 21:20:27 +00001294 Diag(clang::diag::note_drv_command_failed_diag_msg)
1295 << "\n\n********************";
Chad Rosierbe10f982011-08-02 17:58:04 +00001296}
1297
Justin Bogner0cd92482015-07-02 22:52:08 +00001298void Driver::setUpResponseFiles(Compilation &C, Command &Cmd) {
Oleg Ranevskyycd516372016-01-05 19:54:39 +00001299 // Since commandLineFitsWithinSystemLimits() may underestimate system's capacity
Reid Kleckner0290c9c2014-09-15 17:45:39 +00001300 // if the tool does not support response files, there is a chance/ that things
1301 // will just work without a response file, so we silently just skip it.
Justin Bogner0cd92482015-07-02 22:52:08 +00001302 if (Cmd.getCreator().getResponseFilesSupport() == Tool::RF_None ||
Oleg Ranevskyycd516372016-01-05 19:54:39 +00001303 llvm::sys::commandLineFitsWithinSystemLimits(Cmd.getExecutable(), Cmd.getArguments()))
Reid Kleckner0290c9c2014-09-15 17:45:39 +00001304 return;
1305
1306 std::string TmpName = GetTemporaryPath("response", "txt");
Malcolm Parsonsf76f6502016-11-02 10:39:27 +00001307 Cmd.setResponseFile(C.addTempFile(C.getArgs().MakeArgString(TmpName)));
Reid Kleckner0290c9c2014-09-15 17:45:39 +00001308}
1309
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001310int Driver::ExecuteCompilation(
1311 Compilation &C,
1312 SmallVectorImpl<std::pair<int, const Command *>> &FailingCommands) {
Daniel Dunbar38bfda62009-07-01 20:03:04 +00001313 // Just print if -### was present.
1314 if (C.getArgs().hasArg(options::OPT__HASH_HASH_HASH)) {
Hans Wennborgb212b342013-09-12 18:23:34 +00001315 C.getJobs().Print(llvm::errs(), "\n", true);
Daniel Dunbar38bfda62009-07-01 20:03:04 +00001316 return 0;
1317 }
1318
1319 // If there were errors building the compilation, quit now.
Chad Rosierbe10f982011-08-02 17:58:04 +00001320 if (Diags.hasErrorOccurred())
Daniel Dunbar38bfda62009-07-01 20:03:04 +00001321 return 1;
1322
Reid Kleckner0290c9c2014-09-15 17:45:39 +00001323 // Set up response file names for each command, if necessary
Justin Bogner0cd92482015-07-02 22:52:08 +00001324 for (auto &Job : C.getJobs())
1325 setUpResponseFiles(C, Job);
Reid Kleckner0290c9c2014-09-15 17:45:39 +00001326
Justin Bogner0cd92482015-07-02 22:52:08 +00001327 C.ExecuteJobs(C.getJobs(), FailingCommands);
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001328
Daniel Dunbar38bfda62009-07-01 20:03:04 +00001329 // Remove temp files.
1330 C.CleanupFileList(C.getTempFiles());
1331
Daniel Dunbar07494792010-05-22 00:37:20 +00001332 // If the command succeeded, we are done.
Chad Rosierdd60e092013-01-29 20:15:05 +00001333 if (FailingCommands.empty())
1334 return 0;
Daniel Dunbar07494792010-05-22 00:37:20 +00001335
Chad Rosierdd60e092013-01-29 20:15:05 +00001336 // Otherwise, remove result files and print extra information about abnormal
1337 // failures.
Douglas Katzman6bbffc42015-06-25 18:51:37 +00001338 for (const auto &CmdPair : FailingCommands) {
1339 int Res = CmdPair.first;
1340 const Command *FailingCommand = CmdPair.second;
Daniel Dunbar38bfda62009-07-01 20:03:04 +00001341
Chad Rosierdd60e092013-01-29 20:15:05 +00001342 // Remove result files if we're not saving temps.
Reid Kleckner68eb60b2015-02-02 22:41:48 +00001343 if (!isSaveTempsEnabled()) {
Chad Rosierdd60e092013-01-29 20:15:05 +00001344 const JobAction *JA = cast<JobAction>(&FailingCommand->getSource());
1345 C.CleanupFileMap(C.getResultFiles(), JA, true);
1346
1347 // Failure result files are valid unless we crashed.
1348 if (Res < 0)
1349 C.CleanupFileMap(C.getFailureResultFiles(), JA, true);
1350 }
1351
1352 // Print extra information about abnormal failures, if possible.
1353 //
1354 // This is ad-hoc, but we don't want to be excessively noisy. If the result
Justin Bogner5aaf2e72014-06-26 20:59:36 +00001355 // status was 1, assume the command failed normally. In particular, if it
Chad Rosierdd60e092013-01-29 20:15:05 +00001356 // was the compiler then assume it gave a reasonable error code. Failures
1357 // in other tools are less common, and they generally have worse
1358 // diagnostics, so always print the diagnostic there.
1359 const Tool &FailingTool = FailingCommand->getCreator();
1360
1361 if (!FailingCommand->getCreator().hasGoodDiagnostics() || Res != 1) {
1362 // FIXME: See FIXME above regarding result code interpretation.
1363 if (Res < 0)
1364 Diag(clang::diag::err_drv_command_signalled)
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001365 << FailingTool.getShortName();
Chad Rosierdd60e092013-01-29 20:15:05 +00001366 else
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001367 Diag(clang::diag::err_drv_command_failed) << FailingTool.getShortName()
1368 << Res;
Chad Rosierdd60e092013-01-29 20:15:05 +00001369 }
Peter Collingbourne119cfaa2011-11-21 00:01:05 +00001370 }
Chad Rosierdd60e092013-01-29 20:15:05 +00001371 return 0;
Daniel Dunbar38bfda62009-07-01 20:03:04 +00001372}
1373
Daniel Dunbara7b5e212009-04-15 16:34:29 +00001374void Driver::PrintHelp(bool ShowHidden) const {
Hans Wennborg6ddc6902013-07-27 00:23:45 +00001375 unsigned IncludedFlagsBitmask;
1376 unsigned ExcludedFlagsBitmask;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00001377 std::tie(IncludedFlagsBitmask, ExcludedFlagsBitmask) =
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001378 getIncludeExcludeOptionFlagMasks();
Hans Wennborg6ddc6902013-07-27 00:23:45 +00001379
1380 ExcludedFlagsBitmask |= options::NoDriverOption;
1381 if (!ShowHidden)
1382 ExcludedFlagsBitmask |= HelpHidden;
1383
1384 getOpts().PrintHelp(llvm::outs(), Name.c_str(), DriverTitle.c_str(),
George Rimar5dbfa4e2017-07-26 09:10:17 +00001385 IncludedFlagsBitmask, ExcludedFlagsBitmask,
1386 /*ShowAllAliases=*/false);
Daniel Dunbar7c925282009-03-31 21:38:17 +00001387}
1388
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001389void Driver::PrintVersion(const Compilation &C, raw_ostream &OS) const {
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001390 // FIXME: The following handlers should use a callback mechanism, we don't
1391 // know what the client would like to do.
Ted Kremenek4c0df3d2010-01-23 02:11:34 +00001392 OS << getClangFullVersion() << '\n';
Daniel Dunbarb10248802009-03-26 16:09:13 +00001393 const ToolChain &TC = C.getDefaultToolChain();
Daniel Dunbar08e41d62009-07-21 20:06:58 +00001394 OS << "Target: " << TC.getTripleString() << '\n';
Daniel Dunbar10978e42009-06-16 23:32:58 +00001395
1396 // Print the threading model.
Jonathan Roelofsb140a102014-10-03 21:57:44 +00001397 if (Arg *A = C.getArgs().getLastArg(options::OPT_mthread_model)) {
1398 // Don't print if the ToolChain would have barfed on it already
1399 if (TC.isThreadModelSupported(A->getValue()))
1400 OS << "Thread model: " << A->getValue();
1401 } else
1402 OS << "Thread model: " << TC.getThreadModel();
1403 OS << '\n';
Chandler Carruth9ade6a92015-08-05 17:07:33 +00001404
1405 // Print out the install directory.
1406 OS << "InstalledDir: " << InstalledDir << '\n';
Serge Pavlov208ac652018-01-01 13:27:01 +00001407
1408 // If configuration file was used, print its path.
1409 if (!ConfigFile.empty())
1410 OS << "Configuration file: " << ConfigFile << '\n';
Daniel Dunbar5e0f6af2009-03-13 00:51:18 +00001411}
1412
Chris Lattner86ed5b02010-05-05 05:53:24 +00001413/// PrintDiagnosticCategories - Implement the --print-diagnostic-categories
1414/// option.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001415static void PrintDiagnosticCategories(raw_ostream &OS) {
Argyrios Kyrtzidis0e37afa2011-05-25 05:05:01 +00001416 // Skip the empty category.
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001417 for (unsigned i = 1, max = DiagnosticIDs::getNumberOfCategories(); i != max;
1418 ++i)
Argyrios Kyrtzidis0e37afa2011-05-25 05:05:01 +00001419 OS << i << ',' << DiagnosticIDs::getCategoryNameFromID(i) << '\n';
Chris Lattner86ed5b02010-05-05 05:53:24 +00001420}
1421
Yuka Takahashi41789e42018-03-05 08:54:20 +00001422void Driver::HandleAutocompletions(StringRef PassedFlags) const {
Yuka Takahashi503da8f2018-03-05 09:01:31 +00001423 if (PassedFlags == "")
1424 return;
Yuka Takahashi1a895202017-08-29 17:46:46 +00001425 // Print out all options that start with a given argument. This is used for
1426 // shell autocompletion.
1427 std::vector<std::string> SuggestedCompletions;
Yuka Takahashi41789e42018-03-05 08:54:20 +00001428 std::vector<std::string> Flags;
Yuka Takahashi1a895202017-08-29 17:46:46 +00001429
1430 unsigned short DisableFlags =
1431 options::NoDriverOption | options::Unsupported | options::Ignored;
Yuka Takahashi41789e42018-03-05 08:54:20 +00001432
1433 // Parse PassedFlags by "," as all the command-line flags are passed to this
1434 // function separated by ","
1435 StringRef TargetFlags = PassedFlags;
1436 while (TargetFlags != "") {
1437 StringRef CurFlag;
1438 std::tie(CurFlag, TargetFlags) = TargetFlags.split(",");
1439 Flags.push_back(std::string(CurFlag));
Yuka Takahashi1a895202017-08-29 17:46:46 +00001440 }
1441
Yuka Takahashi41789e42018-03-05 08:54:20 +00001442 // We want to show cc1-only options only when clang is invoked with -cc1 or
1443 // -Xclang.
Yuka Takahashi503da8f2018-03-05 09:01:31 +00001444 if (std::find(Flags.begin(), Flags.end(), "-Xclang") != Flags.end() ||
1445 std::find(Flags.begin(), Flags.end(), "-cc1") != Flags.end())
Yuka Takahashi41789e42018-03-05 08:54:20 +00001446 DisableFlags &= ~options::NoDriverOption;
1447
1448 StringRef Cur;
1449 Cur = Flags.at(Flags.size() - 1);
1450 StringRef Prev;
1451 if (Flags.size() >= 2) {
1452 Prev = Flags.at(Flags.size() - 2);
1453 SuggestedCompletions = Opts->suggestValueCompletions(Prev, Cur);
1454 }
1455
1456 if (SuggestedCompletions.empty())
1457 SuggestedCompletions = Opts->suggestValueCompletions(Cur, "");
1458
1459 if (SuggestedCompletions.empty()) {
Yuka Takahashi1a895202017-08-29 17:46:46 +00001460 // If the flag is in the form of "--autocomplete=-foo",
1461 // we were requested to print out all option names that start with "-foo".
1462 // For example, "--autocomplete=-fsyn" is expanded to "-fsyntax-only".
Yuka Takahashi41789e42018-03-05 08:54:20 +00001463 SuggestedCompletions = Opts->findByPrefix(Cur, DisableFlags);
Yuka Takahashi1a895202017-08-29 17:46:46 +00001464
1465 // We have to query the -W flags manually as they're not in the OptTable.
1466 // TODO: Find a good way to add them to OptTable instead and them remove
1467 // this code.
1468 for (StringRef S : DiagnosticIDs::getDiagnosticFlags())
Yuka Takahashi41789e42018-03-05 08:54:20 +00001469 if (S.startswith(Cur))
Yuka Takahashi1a895202017-08-29 17:46:46 +00001470 SuggestedCompletions.push_back(S);
Yuka Takahashi1a895202017-08-29 17:46:46 +00001471 }
1472
1473 // Sort the autocomplete candidates so that shells print them out in a
1474 // deterministic order. We could sort in any way, but we chose
1475 // case-insensitive sorting for consistency with the -help option
1476 // which prints out options in the case-insensitive alphabetical order.
1477 std::sort(SuggestedCompletions.begin(), SuggestedCompletions.end(),
Mandeep Singh Grang8f54ae12017-11-20 18:49:14 +00001478 [](StringRef A, StringRef B) {
1479 if (int X = A.compare_lower(B))
1480 return X < 0;
1481 return A.compare(B) > 0;
1482 });
Yuka Takahashi1a895202017-08-29 17:46:46 +00001483
1484 llvm::outs() << llvm::join(SuggestedCompletions, "\n") << '\n';
1485}
1486
Daniel Dunbarf0eddb82009-03-18 02:55:38 +00001487bool Driver::HandleImmediateArgs(const Compilation &C) {
Daniel Dunbar18974bd2010-06-11 22:00:19 +00001488 // The order these options are handled in gcc is all over the place, but we
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001489 // don't expect inconsistencies w.r.t. that to matter in practice.
Daniel Dunbar7c925282009-03-31 21:38:17 +00001490
Daniel Dunbar1b09e042010-09-17 02:47:28 +00001491 if (C.getArgs().hasArg(options::OPT_dumpmachine)) {
1492 llvm::outs() << C.getDefaultToolChain().getTripleString() << '\n';
1493 return false;
1494 }
1495
Daniel Dunbara9bbcfa2009-04-04 05:17:38 +00001496 if (C.getArgs().hasArg(options::OPT_dumpversion)) {
Daniel Dunbare26e5002011-01-12 00:43:47 +00001497 // Since -dumpversion is only implemented for pedantic GCC compatibility, we
1498 // return an answer which matches our definition of __VERSION__.
1499 //
1500 // If we want to return a more correct answer some day, then we should
1501 // introduce a non-pedantically GCC compatible mode to Clang in which we
1502 // provide sensible definitions for -dumpversion, __VERSION__, etc.
1503 llvm::outs() << "4.2.1\n";
Daniel Dunbara9bbcfa2009-04-04 05:17:38 +00001504 return false;
1505 }
Daniel Dunbarfb3d7472010-06-14 21:23:12 +00001506
Chris Lattner86ed5b02010-05-05 05:53:24 +00001507 if (C.getArgs().hasArg(options::OPT__print_diagnostic_categories)) {
1508 PrintDiagnosticCategories(llvm::outs());
1509 return false;
1510 }
Daniel Dunbara9bbcfa2009-04-04 05:17:38 +00001511
James Molloya3c85b82012-05-01 14:57:16 +00001512 if (C.getArgs().hasArg(options::OPT_help) ||
Daniel Dunbara7b5e212009-04-15 16:34:29 +00001513 C.getArgs().hasArg(options::OPT__help_hidden)) {
1514 PrintHelp(C.getArgs().hasArg(options::OPT__help_hidden));
Daniel Dunbar7c925282009-03-31 21:38:17 +00001515 return false;
1516 }
1517
Daniel Dunbarb0006ae2009-04-02 15:05:41 +00001518 if (C.getArgs().hasArg(options::OPT__version)) {
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001519 // Follow gcc behavior and use stdout for --version and stderr for -v.
Daniel Dunbar08e41d62009-07-21 20:06:58 +00001520 PrintVersion(C, llvm::outs());
Daniel Dunbarb0006ae2009-04-02 15:05:41 +00001521 return false;
1522 }
1523
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001524 if (C.getArgs().hasArg(options::OPT_v) ||
Daniel Dunbarf0eddb82009-03-18 02:55:38 +00001525 C.getArgs().hasArg(options::OPT__HASH_HASH_HASH)) {
Daniel Dunbar08e41d62009-07-21 20:06:58 +00001526 PrintVersion(C, llvm::errs());
Daniel Dunbar5e0f6af2009-03-13 00:51:18 +00001527 SuppressMissingInputWarning = true;
1528 }
1529
Serge Pavlov208ac652018-01-01 13:27:01 +00001530 if (C.getArgs().hasArg(options::OPT_v)) {
1531 if (!SystemConfigDir.empty())
1532 llvm::errs() << "System configuration file directory: "
1533 << SystemConfigDir << "\n";
1534 if (!UserConfigDir.empty())
1535 llvm::errs() << "User configuration file directory: "
1536 << UserConfigDir << "\n";
1537 }
1538
Daniel Dunbarf0eddb82009-03-18 02:55:38 +00001539 const ToolChain &TC = C.getDefaultToolChain();
Chandler Carruth0ae39aa2013-07-30 17:57:09 +00001540
1541 if (C.getArgs().hasArg(options::OPT_v))
1542 TC.printVerboseInfo(llvm::errs());
1543
Meador Inge51208a32017-04-04 21:46:50 +00001544 if (C.getArgs().hasArg(options::OPT_print_resource_dir)) {
Meador Ingea9113952017-04-05 22:27:20 +00001545 llvm::outs() << ResourceDir << '\n';
Meador Inge51208a32017-04-04 21:46:50 +00001546 return false;
1547 }
1548
Daniel Dunbard972e222009-03-20 04:37:21 +00001549 if (C.getArgs().hasArg(options::OPT_print_search_dirs)) {
1550 llvm::outs() << "programs: =";
Douglas Katzman51fe7bf2015-06-23 22:43:50 +00001551 bool separator = false;
1552 for (const std::string &Path : TC.getProgramPaths()) {
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001553 if (separator)
1554 llvm::outs() << ':';
Douglas Katzman51fe7bf2015-06-23 22:43:50 +00001555 llvm::outs() << Path;
1556 separator = true;
Daniel Dunbard972e222009-03-20 04:37:21 +00001557 }
1558 llvm::outs() << "\n";
Peter Collingbournefa9771f2011-09-06 02:08:31 +00001559 llvm::outs() << "libraries: =" << ResourceDir;
Joerg Sonnenberger9c3e69b2011-07-16 10:50:05 +00001560
Sebastian Pop980920a2012-04-16 04:16:43 +00001561 StringRef sysroot = C.getSysRoot();
Joerg Sonnenberger9c3e69b2011-07-16 10:50:05 +00001562
Douglas Katzman51fe7bf2015-06-23 22:43:50 +00001563 for (const std::string &Path : TC.getFilePaths()) {
1564 // Always print a separator. ResourceDir was the first item shown.
Peter Collingbournefa9771f2011-09-06 02:08:31 +00001565 llvm::outs() << ':';
Douglas Katzman51fe7bf2015-06-23 22:43:50 +00001566 // Interpretation of leading '=' is needed only for NetBSD.
1567 if (Path[0] == '=')
Douglas Katzman26eabf62015-06-24 15:10:30 +00001568 llvm::outs() << sysroot << Path.substr(1);
Joerg Sonnenberger9c3e69b2011-07-16 10:50:05 +00001569 else
Douglas Katzman51fe7bf2015-06-23 22:43:50 +00001570 llvm::outs() << Path;
Daniel Dunbard972e222009-03-20 04:37:21 +00001571 }
1572 llvm::outs() << "\n";
Daniel Dunbar7c925282009-03-31 21:38:17 +00001573 return false;
Daniel Dunbard972e222009-03-20 04:37:21 +00001574 }
1575
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001576 // FIXME: The following handlers should use a callback mechanism, we don't
1577 // know what the client would like to do.
Daniel Dunbarf0eddb82009-03-18 02:55:38 +00001578 if (Arg *A = C.getArgs().getLastArg(options::OPT_print_file_name_EQ)) {
Richard Smithbd55daf2012-11-01 04:30:05 +00001579 llvm::outs() << GetFilePath(A->getValue(), TC) << "\n";
Daniel Dunbar5e0f6af2009-03-13 00:51:18 +00001580 return false;
1581 }
1582
Daniel Dunbarf0eddb82009-03-18 02:55:38 +00001583 if (Arg *A = C.getArgs().getLastArg(options::OPT_print_prog_name_EQ)) {
Richard Smithbd55daf2012-11-01 04:30:05 +00001584 llvm::outs() << GetProgramPath(A->getValue(), TC) << "\n";
Daniel Dunbar5e0f6af2009-03-13 00:51:18 +00001585 return false;
1586 }
1587
Yuka Takahashic8068db2017-05-23 18:39:08 +00001588 if (Arg *A = C.getArgs().getLastArg(options::OPT_autocomplete)) {
Yuka Takahashiba5d4af2017-06-20 16:31:31 +00001589 StringRef PassedFlags = A->getValue();
Yuka Takahashi41789e42018-03-05 08:54:20 +00001590 HandleAutocompletions(PassedFlags);
Yuka Takahashic8068db2017-05-23 18:39:08 +00001591 return false;
1592 }
1593
Daniel Dunbarf0eddb82009-03-18 02:55:38 +00001594 if (C.getArgs().hasArg(options::OPT_print_libgcc_file_name)) {
Michal Gorny7cfe4802016-10-10 12:23:40 +00001595 ToolChain::RuntimeLibType RLT = TC.GetRuntimeLibType(C.getArgs());
Leo Li23bb21c2017-08-24 01:51:51 +00001596 const llvm::Triple Triple(TC.ComputeEffectiveClangTriple(C.getArgs()));
1597 RegisterEffectiveTriple TripleRAII(TC, Triple);
Michal Gorny7cfe4802016-10-10 12:23:40 +00001598 switch (RLT) {
1599 case ToolChain::RLT_CompilerRT:
1600 llvm::outs() << TC.getCompilerRT(C.getArgs(), "builtins") << "\n";
1601 break;
1602 case ToolChain::RLT_Libgcc:
1603 llvm::outs() << GetFilePath("libgcc.a", TC) << "\n";
1604 break;
1605 }
Daniel Dunbar5e0f6af2009-03-13 00:51:18 +00001606 return false;
1607 }
1608
Daniel Dunbar1b3ec3a2009-06-16 23:25:22 +00001609 if (C.getArgs().hasArg(options::OPT_print_multi_lib)) {
Douglas Katzmana34b7bf2015-06-30 19:32:57 +00001610 for (const Multilib &Multilib : TC.getMultilibs())
1611 llvm::outs() << Multilib << "\n";
Daniel Dunbar1b3ec3a2009-06-16 23:25:22 +00001612 return false;
1613 }
1614
Jonathan Roelofs2cea1be2014-02-12 03:21:20 +00001615 if (C.getArgs().hasArg(options::OPT_print_multi_directory)) {
Douglas Katzmana34b7bf2015-06-30 19:32:57 +00001616 for (const Multilib &Multilib : TC.getMultilibs()) {
Douglas Katzman6bbffc42015-06-25 18:51:37 +00001617 if (Multilib.gccSuffix().empty())
Jonathan Roelofs2cea1be2014-02-12 03:21:20 +00001618 llvm::outs() << ".\n";
1619 else {
Douglas Katzman6bbffc42015-06-25 18:51:37 +00001620 StringRef Suffix(Multilib.gccSuffix());
Jonathan Roelofs2cea1be2014-02-12 03:21:20 +00001621 assert(Suffix.front() == '/');
1622 llvm::outs() << Suffix.substr(1) << "\n";
1623 }
Jonathan Roelofs3fa96d82014-02-12 01:36:51 +00001624 }
Jonathan Roelofs0e7ec602014-02-12 01:29:25 +00001625 return false;
1626 }
Daniel Dunbar5e0f6af2009-03-13 00:51:18 +00001627 return true;
1628}
1629
Douglas Katzmanfd528672015-06-11 15:05:22 +00001630// Display an action graph human-readably. Action A is the "sink" node
1631// and latest-occuring action. Traversal is in pre-order, visiting the
1632// inputs to each action before printing the action itself.
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001633static unsigned PrintActions1(const Compilation &C, Action *A,
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001634 std::map<Action *, unsigned> &Ids) {
Douglas Katzmanfd528672015-06-11 15:05:22 +00001635 if (Ids.count(A)) // A was already visited.
Daniel Dunbaraaf1ea62009-03-13 12:19:02 +00001636 return Ids[A];
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001637
Daniel Dunbaraaf1ea62009-03-13 12:19:02 +00001638 std::string str;
1639 llvm::raw_string_ostream os(str);
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001640
Daniel Dunbaraaf1ea62009-03-13 12:19:02 +00001641 os << Action::getClassName(A->getKind()) << ", ";
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001642 if (InputAction *IA = dyn_cast<InputAction>(A)) {
Richard Smithbd55daf2012-11-01 04:30:05 +00001643 os << "\"" << IA->getInputArg().getValue() << "\"";
Daniel Dunbaraaf1ea62009-03-13 12:19:02 +00001644 } else if (BindArchAction *BIA = dyn_cast<BindArchAction>(A)) {
Douglas Katzmanb7e8ef02015-06-25 19:37:41 +00001645 os << '"' << BIA->getArchName() << '"' << ", {"
Nico Weber5a459f82016-02-23 19:30:43 +00001646 << PrintActions1(C, *BIA->input_begin(), Ids) << "}";
Samuel Antaod06239d2016-07-15 23:13:27 +00001647 } else if (OffloadAction *OA = dyn_cast<OffloadAction>(A)) {
1648 bool IsFirst = true;
1649 OA->doOnEachDependence(
1650 [&](Action *A, const ToolChain *TC, const char *BoundArch) {
1651 // E.g. for two CUDA device dependences whose bound arch is sm_20 and
1652 // sm_35 this will generate:
1653 // "cuda-device" (nvptx64-nvidia-cuda:sm_20) {#ID}, "cuda-device"
1654 // (nvptx64-nvidia-cuda:sm_35) {#ID}
1655 if (!IsFirst)
1656 os << ", ";
1657 os << '"';
1658 if (TC)
1659 os << A->getOffloadingKindPrefix();
1660 else
1661 os << "host";
1662 os << " (";
1663 os << TC->getTriple().normalize();
1664
1665 if (BoundArch)
1666 os << ":" << BoundArch;
1667 os << ")";
1668 os << '"';
1669 os << " {" << PrintActions1(C, A, Ids) << "}";
1670 IsFirst = false;
1671 });
Daniel Dunbaraaf1ea62009-03-13 12:19:02 +00001672 } else {
Samuel Antaod06239d2016-07-15 23:13:27 +00001673 const ActionList *AL = &A->getInputs();
Artem Belevich0ff05cd2015-07-13 23:27:56 +00001674
Artem Belevich23256752015-09-22 17:23:09 +00001675 if (AL->size()) {
1676 const char *Prefix = "{";
1677 for (Action *PreRequisite : *AL) {
1678 os << Prefix << PrintActions1(C, PreRequisite, Ids);
1679 Prefix = ", ";
1680 }
1681 os << "}";
1682 } else
1683 os << "{}";
Daniel Dunbaraaf1ea62009-03-13 12:19:02 +00001684 }
1685
Samuel Antaod06239d2016-07-15 23:13:27 +00001686 // Append offload info for all options other than the offloading action
1687 // itself (e.g. (cuda-device, sm_20) or (cuda-host)).
1688 std::string offload_str;
1689 llvm::raw_string_ostream offload_os(offload_str);
1690 if (!isa<OffloadAction>(A)) {
1691 auto S = A->getOffloadingKindPrefix();
1692 if (!S.empty()) {
1693 offload_os << ", (" << S;
1694 if (A->getOffloadingArch())
1695 offload_os << ", " << A->getOffloadingArch();
1696 offload_os << ")";
1697 }
1698 }
1699
Daniel Dunbaraaf1ea62009-03-13 12:19:02 +00001700 unsigned Id = Ids.size();
1701 Ids[A] = Id;
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001702 llvm::errs() << Id << ": " << os.str() << ", "
Samuel Antaod06239d2016-07-15 23:13:27 +00001703 << types::getTypeName(A->getType()) << offload_os.str() << "\n";
Daniel Dunbaraaf1ea62009-03-13 12:19:02 +00001704
1705 return Id;
1706}
1707
Douglas Katzmanfd528672015-06-11 15:05:22 +00001708// Print the action graphs in a compilation C.
1709// For example "clang -c file1.c file2.c" is composed of two subgraphs.
Daniel Dunbareb843be2009-03-18 03:13:20 +00001710void Driver::PrintActions(const Compilation &C) const {
Douglas Katzmanb7e8ef02015-06-25 19:37:41 +00001711 std::map<Action *, unsigned> Ids;
1712 for (Action *A : C.getActions())
1713 PrintActions1(C, A, Ids);
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00001714}
1715
Joerg Sonnenberger5fe4a7d2011-05-06 14:05:11 +00001716/// \brief Check whether the given input tree contains any compilation or
1717/// assembly actions.
1718static bool ContainsCompileOrAssembleAction(const Action *A) {
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001719 if (isa<CompileJobAction>(A) || isa<BackendJobAction>(A) ||
Bob Wilson23a55f12014-12-21 07:00:00 +00001720 isa<AssembleJobAction>(A))
Daniel Dunbar00d3d8e2010-06-29 16:38:33 +00001721 return true;
1722
Nico Weber5a459f82016-02-23 19:30:43 +00001723 for (const Action *Input : A->inputs())
Nico Weberfb80f962015-09-19 21:36:51 +00001724 if (ContainsCompileOrAssembleAction(Input))
Daniel Dunbar00d3d8e2010-06-29 16:38:33 +00001725 return true;
1726
1727 return false;
1728}
1729
Artem Belevich5e2a3ec2015-11-17 22:28:40 +00001730void Driver::BuildUniversalActions(Compilation &C, const ToolChain &TC,
1731 const InputList &BAInputs) const {
1732 DerivedArgList &Args = C.getArgs();
1733 ActionList &Actions = C.getActions();
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001734 llvm::PrettyStackTraceString CrashInfo("Building universal build actions");
1735 // Collect the list of architectures. Duplicates are allowed, but should only
1736 // be handled once (in the order seen).
Daniel Dunbare5dc4822009-03-13 20:33:35 +00001737 llvm::StringSet<> ArchNames;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001738 SmallVector<const char *, 4> Archs;
Saleem Abdulrasool688b6bc2014-12-29 19:01:36 +00001739 for (Arg *A : Args) {
Daniel Dunbar0bfb21e2009-11-19 03:26:40 +00001740 if (A->getOption().matches(options::OPT_arch)) {
Daniel Dunbar9c3f7c42009-09-08 23:37:30 +00001741 // Validate the option here; we don't save the type here because its
1742 // particular spelling may participate in other driver choices.
1743 llvm::Triple::ArchType Arch =
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001744 tools::darwin::getArchTypeForMachOArchName(A->getValue());
Daniel Dunbar9c3f7c42009-09-08 23:37:30 +00001745 if (Arch == llvm::Triple::UnknownArch) {
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001746 Diag(clang::diag::err_drv_invalid_arch_name) << A->getAsString(Args);
Daniel Dunbar9c3f7c42009-09-08 23:37:30 +00001747 continue;
1748 }
1749
Daniel Dunbar2da02722009-03-19 07:55:12 +00001750 A->claim();
David Blaikie61b86d42014-11-19 02:56:13 +00001751 if (ArchNames.insert(A->getValue()).second)
Richard Smithbd55daf2012-11-01 04:30:05 +00001752 Archs.push_back(A->getValue());
Daniel Dunbarf479c122009-03-12 18:40:18 +00001753 }
1754 }
1755
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001756 // When there is no explicit arch for this platform, make sure we still bind
1757 // the architecture (to the default) so that -Xarch_ is handled correctly.
Daniel Dunbareb843be2009-03-18 03:13:20 +00001758 if (!Archs.size())
Daniel Dunbarc3bd9f52012-11-08 03:38:26 +00001759 Archs.push_back(Args.MakeArgString(TC.getDefaultUniversalArchName()));
Daniel Dunbarf479c122009-03-12 18:40:18 +00001760
Daniel Dunbarf479c122009-03-12 18:40:18 +00001761 ActionList SingleActions;
Justin Lebar0f3474c2016-02-11 02:00:50 +00001762 BuildActions(C, Args, BAInputs, SingleActions);
Daniel Dunbarf479c122009-03-12 18:40:18 +00001763
Daniel Dunbar6beaf512010-06-04 18:28:41 +00001764 // Add in arch bindings for every top level action, as well as lipo and
1765 // dsymutil steps if needed.
Nico Weberfb80f962015-09-19 21:36:51 +00001766 for (Action* Act : SingleActions) {
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001767 // Make sure we can lipo this kind of output. If not (and it is an actual
1768 // output) then we disallow, since we can't create an output file with the
1769 // right name without overwriting it. We could remove this oddity by just
1770 // changing the output names to include the arch, which would also fix
Daniel Dunbarf479c122009-03-12 18:40:18 +00001771 // -save-temps. Compatibility wins for now.
1772
Daniel Dunbare2ca3bd2009-03-13 17:46:02 +00001773 if (Archs.size() > 1 && !types::canLipoType(Act->getType()))
Daniel Dunbarf479c122009-03-12 18:40:18 +00001774 Diag(clang::diag::err_drv_invalid_output_with_multiple_archs)
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001775 << types::getTypeName(Act->getType());
Daniel Dunbarf479c122009-03-12 18:40:18 +00001776
1777 ActionList Inputs;
Justin Lebar41094612016-01-11 23:07:27 +00001778 for (unsigned i = 0, e = Archs.size(); i != e; ++i)
1779 Inputs.push_back(C.MakeAction<BindArchAction>(Act, Archs[i]));
Daniel Dunbarf479c122009-03-12 18:40:18 +00001780
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001781 // Lipo if necessary, we do it this way because we need to set the arch flag
1782 // so that -Xarch_ gets overwritten.
Daniel Dunbarf479c122009-03-12 18:40:18 +00001783 if (Inputs.size() == 1 || Act->getType() == types::TY_Nothing)
1784 Actions.append(Inputs.begin(), Inputs.end());
1785 else
Justin Lebar41094612016-01-11 23:07:27 +00001786 Actions.push_back(C.MakeAction<LipoJobAction>(Inputs, Act->getType()));
Daniel Dunbar6beaf512010-06-04 18:28:41 +00001787
Eric Christopher65c05fa2012-02-06 19:43:51 +00001788 // Handle debug info queries.
1789 Arg *A = Args.getLastArg(options::OPT_g_Group);
David Blaikie6f9f4eb2012-04-15 21:22:10 +00001790 if (A && !A->getOption().matches(options::OPT_g0) &&
1791 !A->getOption().matches(options::OPT_gstabs) &&
1792 ContainsCompileOrAssembleAction(Actions.back())) {
Chad Rosier62135492012-07-09 17:31:28 +00001793
David Blaikie6f9f4eb2012-04-15 21:22:10 +00001794 // Add a 'dsymutil' step if necessary, when debug info is enabled and we
1795 // have a compile input. We need to run 'dsymutil' ourselves in such cases
Eric Christopher776c26f2013-01-28 17:39:03 +00001796 // because the debug info will refer to a temporary object file which
David Blaikie6f9f4eb2012-04-15 21:22:10 +00001797 // will be removed at the end of the compilation process.
1798 if (Act->getType() == types::TY_Image) {
1799 ActionList Inputs;
1800 Inputs.push_back(Actions.back());
1801 Actions.pop_back();
Justin Lebar41094612016-01-11 23:07:27 +00001802 Actions.push_back(
1803 C.MakeAction<DsymutilJobAction>(Inputs, types::TY_dSYM));
Daniel Dunbar6beaf512010-06-04 18:28:41 +00001804 }
David Blaikie6f9f4eb2012-04-15 21:22:10 +00001805
Ben Langmuir9b9a8d32014-02-06 18:53:25 +00001806 // Verify the debug info output.
Alp Tokere9d2bfc2014-01-17 02:06:23 +00001807 if (Args.hasArg(options::OPT_verify_debug_info)) {
Justin Lebar41094612016-01-11 23:07:27 +00001808 Action* LastAction = Actions.back();
David Blaikie6f9f4eb2012-04-15 21:22:10 +00001809 Actions.pop_back();
Justin Lebar41094612016-01-11 23:07:27 +00001810 Actions.push_back(C.MakeAction<VerifyDebugInfoJobAction>(
1811 LastAction, types::TY_Nothing));
David Blaikie6f9f4eb2012-04-15 21:22:10 +00001812 }
1813 }
Daniel Dunbarf479c122009-03-12 18:40:18 +00001814 }
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00001815}
1816
Hans Wennborg6ee64d52013-08-06 00:20:31 +00001817/// \brief Check that the file referenced by Value exists. If it doesn't,
1818/// issue a diagnostic and return false.
Alp Toker8c8a8752013-12-03 06:53:35 +00001819static bool DiagnoseInputExistence(const Driver &D, const DerivedArgList &Args,
Hans Wennborg12f4f8b2016-04-15 01:12:32 +00001820 StringRef Value, types::ID Ty) {
Hans Wennborg6ee64d52013-08-06 00:20:31 +00001821 if (!D.getCheckInputsExist())
1822 return true;
1823
1824 // stdin always exists.
1825 if (Value == "-")
1826 return true;
1827
1828 SmallString<64> Path(Value);
1829 if (Arg *WorkDir = Args.getLastArg(options::OPT_working_directory)) {
Yaron Keren92e1b622015-03-18 10:17:07 +00001830 if (!llvm::sys::path::is_absolute(Path)) {
Hans Wennborg6ee64d52013-08-06 00:20:31 +00001831 SmallString<64> Directory(WorkDir->getValue());
1832 llvm::sys::path::append(Directory, Value);
1833 Path.assign(Directory);
1834 }
1835 }
1836
1837 if (llvm::sys::fs::exists(Twine(Path)))
1838 return true;
1839
Hans Wennborg12f4f8b2016-04-15 01:12:32 +00001840 if (D.IsCLMode()) {
1841 if (!llvm::sys::path::is_absolute(Twine(Path)) &&
1842 llvm::sys::Process::FindInEnvPath("LIB", Value))
1843 return true;
1844
1845 if (Args.hasArg(options::OPT__SLASH_link) && Ty == types::TY_Object) {
1846 // Arguments to the /link flag might cause the linker to search for object
1847 // and library files in paths we don't know about. Don't error in such
1848 // cases.
1849 return true;
1850 }
1851 }
Hans Wennborg23d26a32014-06-18 17:21:50 +00001852
Yaron Keren92e1b622015-03-18 10:17:07 +00001853 D.Diag(clang::diag::err_drv_no_such_file) << Path;
Hans Wennborg6ee64d52013-08-06 00:20:31 +00001854 return false;
1855}
1856
Chad Rosierecdede82011-08-12 22:08:57 +00001857// Construct a the list of inputs and their types.
Hans Wennborg55362852014-05-02 22:55:30 +00001858void Driver::BuildInputs(const ToolChain &TC, DerivedArgList &Args,
Chad Rosierecdede82011-08-12 22:08:57 +00001859 InputList &Inputs) const {
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001860 // Track the current user specified (-x) input. We also explicitly track the
1861 // argument used to set the type; we only want to claim the type when we
1862 // actually use it, so we warn about unused -x arguments.
Daniel Dunbarc5a5ac52009-03-13 17:57:10 +00001863 types::ID InputType = types::TY_Nothing;
Craig Topper92fc2df2014-05-17 16:56:41 +00001864 Arg *InputTypeArg = nullptr;
Daniel Dunbarc5a5ac52009-03-13 17:57:10 +00001865
Hans Wennborg0d0b19c2013-08-12 18:34:17 +00001866 // The last /TC or /TP option sets the input type to C or C++ globally.
Ehsan Akhgaric249abb2014-09-12 21:44:24 +00001867 if (Arg *TCTP = Args.getLastArgNoClaim(options::OPT__SLASH_TC,
1868 options::OPT__SLASH_TP)) {
Hans Wennborg6ee64d52013-08-06 00:20:31 +00001869 InputTypeArg = TCTP;
Hans Wennborg0d0b19c2013-08-12 18:34:17 +00001870 InputType = TCTP->getOption().matches(options::OPT__SLASH_TC)
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001871 ? types::TY_C
1872 : types::TY_CXX;
Hans Wennborg6ee64d52013-08-06 00:20:31 +00001873
Richard Smith0aef3052017-02-18 01:14:43 +00001874 Arg *Previous = nullptr;
Hans Wennborg0d0b19c2013-08-12 18:34:17 +00001875 bool ShowNote = false;
Richard Smith0aef3052017-02-18 01:14:43 +00001876 for (Arg *A : Args.filtered(options::OPT__SLASH_TC, options::OPT__SLASH_TP)) {
1877 if (Previous) {
1878 Diag(clang::diag::warn_drv_overriding_flag_option)
1879 << Previous->getSpelling() << A->getSpelling();
1880 ShowNote = true;
1881 }
1882 Previous = A;
Hans Wennborg6ee64d52013-08-06 00:20:31 +00001883 }
Hans Wennborg0d0b19c2013-08-12 18:34:17 +00001884 if (ShowNote)
1885 Diag(clang::diag::note_drv_t_option_is_global);
Hans Wennborg6ee64d52013-08-06 00:20:31 +00001886
1887 // No driver mode exposes -x and /TC or /TP; we don't support mixing them.
1888 assert(!Args.hasArg(options::OPT_x) && "-x and /TC or /TP is not allowed");
1889 }
1890
Saleem Abdulrasool688b6bc2014-12-29 19:01:36 +00001891 for (Arg *A : Args) {
Michael J. Spencerad3ccc32012-08-20 21:41:17 +00001892 if (A->getOption().getKind() == Option::InputClass) {
Richard Smithbd55daf2012-11-01 04:30:05 +00001893 const char *Value = A->getValue();
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00001894 types::ID Ty = types::TY_INVALID;
1895
1896 // Infer the input type if necessary.
Daniel Dunbarc5a5ac52009-03-13 17:57:10 +00001897 if (InputType == types::TY_Nothing) {
1898 // If there was an explicit arg for this, claim it.
1899 if (InputTypeArg)
1900 InputTypeArg->claim();
1901
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00001902 // stdin must be handled specially.
1903 if (memcmp(Value, "-", 2) == 0) {
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001904 // If running with -E, treat as a C input (this changes the builtin
1905 // macros, for example). This may be overridden by -ObjC below.
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00001906 //
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001907 // Otherwise emit an error but still use a valid type to avoid
1908 // spurious errors (e.g., no inputs).
Hans Wennborg70850d82013-07-18 20:29:38 +00001909 if (!Args.hasArgNoClaim(options::OPT_E) && !CCCIsCPP())
Hans Wennborgcfdd8b52014-01-29 01:04:40 +00001910 Diag(IsCLMode() ? clang::diag::err_drv_unknown_stdin_type_clang_cl
1911 : clang::diag::err_drv_unknown_stdin_type);
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00001912 Ty = types::TY_C;
1913 } else {
Joerg Sonnenbergerbdbdf702011-03-16 22:45:02 +00001914 // Otherwise lookup by extension.
1915 // Fallback is C if invoked as C preprocessor or Object otherwise.
1916 // We use a host hook here because Darwin at least has its own
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001917 // idea of what .s is.
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00001918 if (const char *Ext = strrchr(Value, '.'))
Daniel Dunbarcc7df6c2010-08-02 05:43:56 +00001919 Ty = TC.LookupTypeForExtension(Ext + 1);
Daniel Dunbarea9f0322009-03-20 23:39:23 +00001920
Joerg Sonnenbergerbdbdf702011-03-16 22:45:02 +00001921 if (Ty == types::TY_INVALID) {
Hans Wennborg70850d82013-07-18 20:29:38 +00001922 if (CCCIsCPP())
Joerg Sonnenbergerbdbdf702011-03-16 22:45:02 +00001923 Ty = types::TY_C;
1924 else
1925 Ty = types::TY_Object;
1926 }
Daniel Dunbar0ac94452010-02-17 20:32:58 +00001927
1928 // If the driver is invoked as C++ compiler (like clang++ or c++) it
1929 // should autodetect some input files as C++ for g++ compatibility.
Hans Wennborg70850d82013-07-18 20:29:38 +00001930 if (CCCIsCXX()) {
Daniel Dunbar0ac94452010-02-17 20:32:58 +00001931 types::ID OldTy = Ty;
1932 Ty = types::lookupCXXTypeForCType(Ty);
1933
1934 if (Ty != OldTy)
1935 Diag(clang::diag::warn_drv_treating_input_as_cxx)
Douglas Katzmana67e50c2015-06-26 15:47:46 +00001936 << getTypeName(OldTy) << getTypeName(Ty);
Daniel Dunbar0ac94452010-02-17 20:32:58 +00001937 }
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00001938 }
1939
Daniel Dunbar82b22102009-05-18 21:47:54 +00001940 // -ObjC and -ObjC++ override the default language, but only for "source
1941 // files". We just treat everything that isn't a linker input as a
1942 // source file.
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001943 //
Daniel Dunbar82b22102009-05-18 21:47:54 +00001944 // FIXME: Clean this up if we move the phase sequence into the type.
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00001945 if (Ty != types::TY_Object) {
1946 if (Args.hasArg(options::OPT_ObjC))
1947 Ty = types::TY_ObjC;
1948 else if (Args.hasArg(options::OPT_ObjCXX))
1949 Ty = types::TY_ObjCXX;
1950 }
1951 } else {
1952 assert(InputTypeArg && "InputType set w/o InputTypeArg");
Ehsan Akhgari7e954ea2014-09-12 18:15:10 +00001953 if (!InputTypeArg->getOption().matches(options::OPT_x)) {
1954 // If emulating cl.exe, make sure that /TC and /TP don't affect input
1955 // object files.
1956 const char *Ext = strrchr(Value, '.');
1957 if (Ext && TC.LookupTypeForExtension(Ext + 1) == types::TY_Object)
1958 Ty = types::TY_Object;
1959 }
1960 if (Ty == types::TY_INVALID) {
1961 Ty = InputType;
1962 InputTypeArg->claim();
1963 }
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00001964 }
1965
Hans Wennborg12f4f8b2016-04-15 01:12:32 +00001966 if (DiagnoseInputExistence(*this, Args, Value, Ty))
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00001967 Inputs.push_back(std::make_pair(Ty, A));
1968
Hans Wennborg6ee64d52013-08-06 00:20:31 +00001969 } else if (A->getOption().matches(options::OPT__SLASH_Tc)) {
1970 StringRef Value = A->getValue();
Hans Wennborg12f4f8b2016-04-15 01:12:32 +00001971 if (DiagnoseInputExistence(*this, Args, Value, types::TY_C)) {
David Blaikie0aaa7622017-01-13 17:34:15 +00001972 Arg *InputArg = MakeInputArg(Args, *Opts, A->getValue());
Hans Wennborg6ee64d52013-08-06 00:20:31 +00001973 Inputs.push_back(std::make_pair(types::TY_C, InputArg));
1974 }
1975 A->claim();
1976 } else if (A->getOption().matches(options::OPT__SLASH_Tp)) {
1977 StringRef Value = A->getValue();
Hans Wennborg12f4f8b2016-04-15 01:12:32 +00001978 if (DiagnoseInputExistence(*this, Args, Value, types::TY_CXX)) {
David Blaikie0aaa7622017-01-13 17:34:15 +00001979 Arg *InputArg = MakeInputArg(Args, *Opts, A->getValue());
Hans Wennborg6ee64d52013-08-06 00:20:31 +00001980 Inputs.push_back(std::make_pair(types::TY_CXX, InputArg));
1981 }
1982 A->claim();
Michael J. Spencer66e2b202012-10-19 22:37:06 +00001983 } else if (A->getOption().hasFlag(options::LinkerInput)) {
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001984 // Just treat as object type, we could make a special type for this if
1985 // necessary.
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00001986 Inputs.push_back(std::make_pair(types::TY_Object, A));
1987
Daniel Dunbar0bfb21e2009-11-19 03:26:40 +00001988 } else if (A->getOption().matches(options::OPT_x)) {
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001989 InputTypeArg = A;
Richard Smithbd55daf2012-11-01 04:30:05 +00001990 InputType = types::lookupTypeForTypeSpecifier(A->getValue());
Chad Rosier706c2352012-04-07 00:01:31 +00001991 A->claim();
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00001992
1993 // Follow gcc behavior and treat as linker input for invalid -x
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00001994 // options. Its not clear why we shouldn't just revert to unknown; but
Michael J. Spencer1a4fe8c2010-12-17 21:22:33 +00001995 // this isn't very important, we might as well be bug compatible.
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00001996 if (!InputType) {
Richard Smithbd55daf2012-11-01 04:30:05 +00001997 Diag(clang::diag::err_drv_unknown_language) << A->getValue();
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00001998 InputType = types::TY_Object;
1999 }
Hans Wennborg091f1b62017-01-27 17:09:41 +00002000 } else if (A->getOption().getID() == options::OPT__SLASH_U) {
2001 assert(A->getNumValues() == 1 && "The /U option has one value.");
2002 StringRef Val = A->getValue(0);
2003 if (Val.find_first_of("/\\") != StringRef::npos) {
2004 // Warn about e.g. "/Users/me/myfile.c".
2005 Diag(diag::warn_slash_u_filename) << Val;
2006 Diag(diag::note_use_dashdash);
2007 }
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00002008 }
2009 }
Hans Wennborg70850d82013-07-18 20:29:38 +00002010 if (CCCIsCPP() && Inputs.empty()) {
Joerg Sonnenbergerb86f5f42011-03-06 23:31:01 +00002011 // If called as standalone preprocessor, stdin is processed
2012 // if no other input is present.
David Blaikie0aaa7622017-01-13 17:34:15 +00002013 Arg *A = MakeInputArg(Args, *Opts, "-");
Joerg Sonnenbergerb86f5f42011-03-06 23:31:01 +00002014 Inputs.push_back(std::make_pair(types::TY_C, A));
2015 }
Chad Rosierecdede82011-08-12 22:08:57 +00002016}
2017
Samuel Antao64e965e2016-09-30 15:34:19 +00002018namespace {
2019/// Provides a convenient interface for different programming models to generate
2020/// the required device actions.
2021class OffloadingActionBuilder final {
2022 /// Flag used to trace errors in the builder.
2023 bool IsValid = false;
2024
2025 /// The compilation that is using this builder.
2026 Compilation &C;
2027
Samuel Antao64e965e2016-09-30 15:34:19 +00002028 /// Map between an input argument and the offload kinds used to process it.
2029 std::map<const Arg *, unsigned> InputArgToOffloadKindMap;
2030
2031 /// Builder interface. It doesn't build anything or keep any state.
2032 class DeviceActionBuilder {
2033 public:
2034 typedef llvm::SmallVector<phases::ID, phases::MaxNumberOfPhases> PhasesTy;
2035
2036 enum ActionBuilderReturnCode {
2037 // The builder acted successfully on the current action.
2038 ABRT_Success,
2039 // The builder didn't have to act on the current action.
2040 ABRT_Inactive,
2041 // The builder was successful and requested the host action to not be
2042 // generated.
2043 ABRT_Ignore_Host,
2044 };
2045
2046 protected:
2047 /// Compilation associated with this builder.
2048 Compilation &C;
2049
2050 /// Tool chains associated with this builder. The same programming
2051 /// model may have associated one or more tool chains.
2052 SmallVector<const ToolChain *, 2> ToolChains;
2053
2054 /// The derived arguments associated with this builder.
2055 DerivedArgList &Args;
2056
2057 /// The inputs associated with this builder.
2058 const Driver::InputList &Inputs;
2059
2060 /// The associated offload kind.
2061 Action::OffloadKind AssociatedOffloadKind = Action::OFK_None;
2062
2063 public:
2064 DeviceActionBuilder(Compilation &C, DerivedArgList &Args,
2065 const Driver::InputList &Inputs,
2066 Action::OffloadKind AssociatedOffloadKind)
2067 : C(C), Args(Args), Inputs(Inputs),
2068 AssociatedOffloadKind(AssociatedOffloadKind) {}
2069 virtual ~DeviceActionBuilder() {}
2070
2071 /// Fill up the array \a DA with all the device dependences that should be
2072 /// added to the provided host action \a HostAction. By default it is
2073 /// inactive.
2074 virtual ActionBuilderReturnCode
Samuel Antao28c4f182016-10-27 17:08:03 +00002075 getDeviceDependences(OffloadAction::DeviceDependences &DA,
2076 phases::ID CurPhase, phases::ID FinalPhase,
2077 PhasesTy &Phases) {
Samuel Antao64e965e2016-09-30 15:34:19 +00002078 return ABRT_Inactive;
2079 }
2080
2081 /// Update the state to include the provided host action \a HostAction as a
2082 /// dependency of the current device action. By default it is inactive.
2083 virtual ActionBuilderReturnCode addDeviceDepences(Action *HostAction) {
2084 return ABRT_Inactive;
2085 }
2086
2087 /// Append top level actions generated by the builder. Return true if errors
2088 /// were found.
2089 virtual void appendTopLevelActions(ActionList &AL) {}
2090
2091 /// Append linker actions generated by the builder. Return true if errors
2092 /// were found.
2093 virtual void appendLinkDependences(OffloadAction::DeviceDependences &DA) {}
2094
2095 /// Initialize the builder. Return true if any initialization errors are
2096 /// found.
2097 virtual bool initialize() { return false; }
2098
Samuel Antao69d6f312016-10-27 17:50:43 +00002099 /// Return true if the builder can use bundling/unbundling.
2100 virtual bool canUseBundlerUnbundler() const { return false; }
2101
Samuel Antao64e965e2016-09-30 15:34:19 +00002102 /// Return true if this builder is valid. We have a valid builder if we have
2103 /// associated device tool chains.
2104 bool isValid() { return !ToolChains.empty(); }
2105
2106 /// Return the associated offload kind.
2107 Action::OffloadKind getAssociatedOffloadKind() {
2108 return AssociatedOffloadKind;
2109 }
2110 };
2111
2112 /// \brief CUDA action builder. It injects device code in the host backend
2113 /// action.
2114 class CudaActionBuilder final : public DeviceActionBuilder {
2115 /// Flags to signal if the user requested host-only or device-only
2116 /// compilation.
2117 bool CompileHostOnly = false;
2118 bool CompileDeviceOnly = false;
2119
2120 /// List of GPU architectures to use in this compilation.
2121 SmallVector<CudaArch, 4> GpuArchList;
2122
2123 /// The CUDA actions for the current input.
2124 ActionList CudaDeviceActions;
2125
2126 /// The CUDA fat binary if it was generated for the current input.
2127 Action *CudaFatBinary = nullptr;
2128
2129 /// Flag that is set to true if this builder acted on the current input.
2130 bool IsActive = false;
2131
2132 public:
2133 CudaActionBuilder(Compilation &C, DerivedArgList &Args,
2134 const Driver::InputList &Inputs)
2135 : DeviceActionBuilder(C, Args, Inputs, Action::OFK_Cuda) {}
2136
2137 ActionBuilderReturnCode
Samuel Antao28c4f182016-10-27 17:08:03 +00002138 getDeviceDependences(OffloadAction::DeviceDependences &DA,
2139 phases::ID CurPhase, phases::ID FinalPhase,
2140 PhasesTy &Phases) override {
Samuel Antao64e965e2016-09-30 15:34:19 +00002141 if (!IsActive)
2142 return ABRT_Inactive;
2143
2144 // If we don't have more CUDA actions, we don't have any dependences to
2145 // create for the host.
2146 if (CudaDeviceActions.empty())
2147 return ABRT_Success;
2148
2149 assert(CudaDeviceActions.size() == GpuArchList.size() &&
2150 "Expecting one action per GPU architecture.");
2151 assert(!CompileHostOnly &&
2152 "Not expecting CUDA actions in host-only compilation.");
2153
2154 // If we are generating code for the device or we are in a backend phase,
2155 // we attempt to generate the fat binary. We compile each arch to ptx and
2156 // assemble to cubin, then feed the cubin *and* the ptx into a device
2157 // "link" action, which uses fatbinary to combine these cubins into one
2158 // fatbin. The fatbin is then an input to the host action if not in
2159 // device-only mode.
2160 if (CompileDeviceOnly || CurPhase == phases::Backend) {
2161 ActionList DeviceActions;
2162 for (unsigned I = 0, E = GpuArchList.size(); I != E; ++I) {
2163 // Produce the device action from the current phase up to the assemble
2164 // phase.
2165 for (auto Ph : Phases) {
2166 // Skip the phases that were already dealt with.
2167 if (Ph < CurPhase)
2168 continue;
2169 // We have to be consistent with the host final phase.
2170 if (Ph > FinalPhase)
2171 break;
2172
2173 CudaDeviceActions[I] = C.getDriver().ConstructPhaseAction(
Artem Belevichecb178b2018-03-21 22:22:59 +00002174 C, Args, Ph, CudaDeviceActions[I], Action::OFK_Cuda);
Samuel Antao64e965e2016-09-30 15:34:19 +00002175
2176 if (Ph == phases::Assemble)
2177 break;
2178 }
2179
2180 // If we didn't reach the assemble phase, we can't generate the fat
2181 // binary. We don't need to generate the fat binary if we are not in
2182 // device-only mode.
2183 if (!isa<AssembleJobAction>(CudaDeviceActions[I]) ||
2184 CompileDeviceOnly)
2185 continue;
2186
2187 Action *AssembleAction = CudaDeviceActions[I];
2188 assert(AssembleAction->getType() == types::TY_Object);
2189 assert(AssembleAction->getInputs().size() == 1);
2190
2191 Action *BackendAction = AssembleAction->getInputs()[0];
2192 assert(BackendAction->getType() == types::TY_PP_Asm);
2193
2194 for (auto &A : {AssembleAction, BackendAction}) {
2195 OffloadAction::DeviceDependences DDep;
2196 DDep.add(*A, *ToolChains.front(), CudaArchToString(GpuArchList[I]),
2197 Action::OFK_Cuda);
2198 DeviceActions.push_back(
2199 C.MakeAction<OffloadAction>(DDep, A->getType()));
2200 }
2201 }
2202
2203 // We generate the fat binary if we have device input actions.
2204 if (!DeviceActions.empty()) {
2205 CudaFatBinary =
2206 C.MakeAction<LinkJobAction>(DeviceActions, types::TY_CUDA_FATBIN);
2207
2208 if (!CompileDeviceOnly) {
2209 DA.add(*CudaFatBinary, *ToolChains.front(), /*BoundArch=*/nullptr,
2210 Action::OFK_Cuda);
2211 // Clear the fat binary, it is already a dependence to an host
2212 // action.
2213 CudaFatBinary = nullptr;
2214 }
2215
2216 // Remove the CUDA actions as they are already connected to an host
2217 // action or fat binary.
2218 CudaDeviceActions.clear();
2219 }
2220
2221 // We avoid creating host action in device-only mode.
2222 return CompileDeviceOnly ? ABRT_Ignore_Host : ABRT_Success;
Samuel Antao5b1a89a2016-10-27 00:53:34 +00002223 } else if (CurPhase > phases::Backend) {
2224 // If we are past the backend phase and still have a device action, we
2225 // don't have to do anything as this action is already a device
2226 // top-level action.
2227 return ABRT_Success;
Samuel Antao64e965e2016-09-30 15:34:19 +00002228 }
2229
2230 assert(CurPhase < phases::Backend && "Generating single CUDA "
2231 "instructions should only occur "
2232 "before the backend phase!");
2233
2234 // By default, we produce an action for each device arch.
2235 for (Action *&A : CudaDeviceActions)
2236 A = C.getDriver().ConstructPhaseAction(C, Args, CurPhase, A);
2237
2238 return ABRT_Success;
2239 }
2240
2241 ActionBuilderReturnCode addDeviceDepences(Action *HostAction) override {
2242 // While generating code for CUDA, we only depend on the host input action
2243 // to trigger the creation of all the CUDA device actions.
2244
2245 // If we are dealing with an input action, replicate it for each GPU
2246 // architecture. If we are in host-only mode we return 'success' so that
2247 // the host uses the CUDA offload kind.
2248 if (auto *IA = dyn_cast<InputAction>(HostAction)) {
2249 assert(!GpuArchList.empty() &&
2250 "We should have at least one GPU architecture.");
2251
2252 // If the host input is not CUDA, we don't need to bother about this
2253 // input.
2254 if (IA->getType() != types::TY_CUDA) {
2255 // The builder will ignore this input.
2256 IsActive = false;
2257 return ABRT_Inactive;
2258 }
2259
2260 // Set the flag to true, so that the builder acts on the current input.
2261 IsActive = true;
2262
2263 if (CompileHostOnly)
2264 return ABRT_Success;
2265
2266 // Replicate inputs for each GPU architecture.
2267 for (unsigned I = 0, E = GpuArchList.size(); I != E; ++I)
2268 CudaDeviceActions.push_back(C.MakeAction<InputAction>(
2269 IA->getInputArg(), types::TY_CUDA_DEVICE));
2270
2271 return ABRT_Success;
2272 }
2273
2274 return IsActive ? ABRT_Success : ABRT_Inactive;
2275 }
2276
2277 void appendTopLevelActions(ActionList &AL) override {
2278 // Utility to append actions to the top level list.
2279 auto AddTopLevel = [&](Action *A, CudaArch BoundArch) {
2280 OffloadAction::DeviceDependences Dep;
2281 Dep.add(*A, *ToolChains.front(), CudaArchToString(BoundArch),
2282 Action::OFK_Cuda);
2283 AL.push_back(C.MakeAction<OffloadAction>(Dep, A->getType()));
2284 };
2285
2286 // If we have a fat binary, add it to the list.
2287 if (CudaFatBinary) {
2288 AddTopLevel(CudaFatBinary, CudaArch::UNKNOWN);
2289 CudaDeviceActions.clear();
2290 CudaFatBinary = nullptr;
2291 return;
2292 }
2293
2294 if (CudaDeviceActions.empty())
2295 return;
2296
2297 // If we have CUDA actions at this point, that's because we have a have
2298 // partial compilation, so we should have an action for each GPU
2299 // architecture.
2300 assert(CudaDeviceActions.size() == GpuArchList.size() &&
2301 "Expecting one action per GPU architecture.");
2302 assert(ToolChains.size() == 1 &&
2303 "Expecting to have a sing CUDA toolchain.");
2304 for (unsigned I = 0, E = GpuArchList.size(); I != E; ++I)
2305 AddTopLevel(CudaDeviceActions[I], GpuArchList[I]);
2306
2307 CudaDeviceActions.clear();
2308 }
2309
2310 bool initialize() override {
2311 // We don't need to support CUDA.
2312 if (!C.hasOffloadToolChain<Action::OFK_Cuda>())
2313 return false;
2314
2315 const ToolChain *HostTC = C.getSingleOffloadToolChain<Action::OFK_Host>();
2316 assert(HostTC && "No toolchain for host compilation.");
2317 if (HostTC->getTriple().isNVPTX()) {
2318 // We do not support targeting NVPTX for host compilation. Throw
2319 // an error and abort pipeline construction early so we don't trip
2320 // asserts that assume device-side compilation.
2321 C.getDriver().Diag(diag::err_drv_cuda_nvptx_host);
2322 return true;
2323 }
2324
2325 ToolChains.push_back(C.getSingleOffloadToolChain<Action::OFK_Cuda>());
2326
2327 Arg *PartialCompilationArg = Args.getLastArg(
2328 options::OPT_cuda_host_only, options::OPT_cuda_device_only,
2329 options::OPT_cuda_compile_host_device);
2330 CompileHostOnly = PartialCompilationArg &&
2331 PartialCompilationArg->getOption().matches(
2332 options::OPT_cuda_host_only);
2333 CompileDeviceOnly = PartialCompilationArg &&
2334 PartialCompilationArg->getOption().matches(
2335 options::OPT_cuda_device_only);
2336
2337 // Collect all cuda_gpu_arch parameters, removing duplicates.
Artem Belevicha424e882016-12-09 22:59:17 +00002338 std::set<CudaArch> GpuArchs;
Samuel Antao64e965e2016-09-30 15:34:19 +00002339 bool Error = false;
2340 for (Arg *A : Args) {
Artem Belevicha424e882016-12-09 22:59:17 +00002341 if (!(A->getOption().matches(options::OPT_cuda_gpu_arch_EQ) ||
2342 A->getOption().matches(options::OPT_no_cuda_gpu_arch_EQ)))
Samuel Antao64e965e2016-09-30 15:34:19 +00002343 continue;
2344 A->claim();
2345
Artem Belevicha424e882016-12-09 22:59:17 +00002346 const StringRef ArchStr = A->getValue();
2347 if (A->getOption().matches(options::OPT_no_cuda_gpu_arch_EQ) &&
2348 ArchStr == "all") {
2349 GpuArchs.clear();
2350 continue;
2351 }
Samuel Antao64e965e2016-09-30 15:34:19 +00002352 CudaArch Arch = StringToCudaArch(ArchStr);
2353 if (Arch == CudaArch::UNKNOWN) {
2354 C.getDriver().Diag(clang::diag::err_drv_cuda_bad_gpu_arch) << ArchStr;
2355 Error = true;
Artem Belevicha424e882016-12-09 22:59:17 +00002356 } else if (A->getOption().matches(options::OPT_cuda_gpu_arch_EQ))
2357 GpuArchs.insert(Arch);
2358 else if (A->getOption().matches(options::OPT_no_cuda_gpu_arch_EQ))
2359 GpuArchs.erase(Arch);
2360 else
2361 llvm_unreachable("Unexpected option.");
Samuel Antao64e965e2016-09-30 15:34:19 +00002362 }
2363
Artem Belevicha424e882016-12-09 22:59:17 +00002364 // Collect list of GPUs remaining in the set.
2365 for (CudaArch Arch : GpuArchs)
2366 GpuArchList.push_back(Arch);
2367
2368 // Default to sm_20 which is the lowest common denominator for
2369 // supported GPUs. sm_20 code should work correctly, if
2370 // suboptimally, on all newer GPUs.
Samuel Antao64e965e2016-09-30 15:34:19 +00002371 if (GpuArchList.empty())
2372 GpuArchList.push_back(CudaArch::SM_20);
2373
2374 return Error;
2375 }
2376 };
2377
Samuel Antao28c4f182016-10-27 17:08:03 +00002378 /// OpenMP action builder. The host bitcode is passed to the device frontend
2379 /// and all the device linked images are passed to the host link phase.
2380 class OpenMPActionBuilder final : public DeviceActionBuilder {
2381 /// The OpenMP actions for the current input.
2382 ActionList OpenMPDeviceActions;
2383
2384 /// The linker inputs obtained for each toolchain.
2385 SmallVector<ActionList, 8> DeviceLinkerInputs;
2386
2387 public:
2388 OpenMPActionBuilder(Compilation &C, DerivedArgList &Args,
2389 const Driver::InputList &Inputs)
2390 : DeviceActionBuilder(C, Args, Inputs, Action::OFK_OpenMP) {}
2391
2392 ActionBuilderReturnCode
2393 getDeviceDependences(OffloadAction::DeviceDependences &DA,
2394 phases::ID CurPhase, phases::ID FinalPhase,
2395 PhasesTy &Phases) override {
2396
2397 // We should always have an action for each input.
2398 assert(OpenMPDeviceActions.size() == ToolChains.size() &&
2399 "Number of OpenMP actions and toolchains do not match.");
2400
2401 // The host only depends on device action in the linking phase, when all
2402 // the device images have to be embedded in the host image.
2403 if (CurPhase == phases::Link) {
2404 assert(ToolChains.size() == DeviceLinkerInputs.size() &&
2405 "Toolchains and linker inputs sizes do not match.");
2406 auto LI = DeviceLinkerInputs.begin();
2407 for (auto *A : OpenMPDeviceActions) {
2408 LI->push_back(A);
2409 ++LI;
2410 }
2411
2412 // We passed the device action as a host dependence, so we don't need to
2413 // do anything else with them.
2414 OpenMPDeviceActions.clear();
2415 return ABRT_Success;
2416 }
2417
2418 // By default, we produce an action for each device arch.
2419 for (Action *&A : OpenMPDeviceActions)
2420 A = C.getDriver().ConstructPhaseAction(C, Args, CurPhase, A);
2421
2422 return ABRT_Success;
2423 }
2424
2425 ActionBuilderReturnCode addDeviceDepences(Action *HostAction) override {
2426
2427 // If this is an input action replicate it for each OpenMP toolchain.
2428 if (auto *IA = dyn_cast<InputAction>(HostAction)) {
2429 OpenMPDeviceActions.clear();
2430 for (unsigned I = 0; I < ToolChains.size(); ++I)
2431 OpenMPDeviceActions.push_back(
2432 C.MakeAction<InputAction>(IA->getInputArg(), IA->getType()));
2433 return ABRT_Success;
2434 }
2435
Samuel Antaofab4f372016-10-27 18:00:51 +00002436 // If this is an unbundling action use it as is for each OpenMP toolchain.
2437 if (auto *UA = dyn_cast<OffloadUnbundlingJobAction>(HostAction)) {
2438 OpenMPDeviceActions.clear();
2439 for (unsigned I = 0; I < ToolChains.size(); ++I) {
2440 OpenMPDeviceActions.push_back(UA);
2441 UA->registerDependentActionInfo(
2442 ToolChains[I], /*BoundArch=*/StringRef(), Action::OFK_OpenMP);
2443 }
2444 return ABRT_Success;
2445 }
2446
Samuel Antao28c4f182016-10-27 17:08:03 +00002447 // When generating code for OpenMP we use the host compile phase result as
2448 // a dependence to the device compile phase so that it can learn what
2449 // declarations should be emitted. However, this is not the only use for
2450 // the host action, so we prevent it from being collapsed.
2451 if (isa<CompileJobAction>(HostAction)) {
2452 HostAction->setCannotBeCollapsedWithNextDependentAction();
2453 assert(ToolChains.size() == OpenMPDeviceActions.size() &&
2454 "Toolchains and device action sizes do not match.");
2455 OffloadAction::HostDependence HDep(
2456 *HostAction, *C.getSingleOffloadToolChain<Action::OFK_Host>(),
2457 /*BoundArch=*/nullptr, Action::OFK_OpenMP);
2458 auto TC = ToolChains.begin();
2459 for (Action *&A : OpenMPDeviceActions) {
2460 assert(isa<CompileJobAction>(A));
2461 OffloadAction::DeviceDependences DDep;
2462 DDep.add(*A, **TC, /*BoundArch=*/nullptr, Action::OFK_OpenMP);
2463 A = C.MakeAction<OffloadAction>(HDep, DDep);
2464 ++TC;
2465 }
2466 }
2467 return ABRT_Success;
2468 }
2469
Samuel Antao69d6f312016-10-27 17:50:43 +00002470 void appendTopLevelActions(ActionList &AL) override {
2471 if (OpenMPDeviceActions.empty())
2472 return;
2473
2474 // We should always have an action for each input.
2475 assert(OpenMPDeviceActions.size() == ToolChains.size() &&
2476 "Number of OpenMP actions and toolchains do not match.");
2477
2478 // Append all device actions followed by the proper offload action.
2479 auto TI = ToolChains.begin();
2480 for (auto *A : OpenMPDeviceActions) {
2481 OffloadAction::DeviceDependences Dep;
2482 Dep.add(*A, **TI, /*BoundArch=*/nullptr, Action::OFK_OpenMP);
2483 AL.push_back(C.MakeAction<OffloadAction>(Dep, A->getType()));
2484 ++TI;
2485 }
2486 // We no longer need the action stored in this builder.
2487 OpenMPDeviceActions.clear();
2488 }
2489
Samuel Antao28c4f182016-10-27 17:08:03 +00002490 void appendLinkDependences(OffloadAction::DeviceDependences &DA) override {
2491 assert(ToolChains.size() == DeviceLinkerInputs.size() &&
2492 "Toolchains and linker inputs sizes do not match.");
2493
2494 // Append a new link action for each device.
2495 auto TC = ToolChains.begin();
2496 for (auto &LI : DeviceLinkerInputs) {
2497 auto *DeviceLinkAction =
2498 C.MakeAction<LinkJobAction>(LI, types::TY_Image);
2499 DA.add(*DeviceLinkAction, **TC, /*BoundArch=*/nullptr,
2500 Action::OFK_OpenMP);
2501 ++TC;
2502 }
2503 }
2504
2505 bool initialize() override {
2506 // Get the OpenMP toolchains. If we don't get any, the action builder will
2507 // know there is nothing to do related to OpenMP offloading.
2508 auto OpenMPTCRange = C.getOffloadToolChains<Action::OFK_OpenMP>();
2509 for (auto TI = OpenMPTCRange.first, TE = OpenMPTCRange.second; TI != TE;
2510 ++TI)
2511 ToolChains.push_back(TI->second);
2512
2513 DeviceLinkerInputs.resize(ToolChains.size());
2514 return false;
2515 }
Samuel Antao69d6f312016-10-27 17:50:43 +00002516
2517 bool canUseBundlerUnbundler() const override {
2518 // OpenMP should use bundled files whenever possible.
2519 return true;
2520 }
Samuel Antao28c4f182016-10-27 17:08:03 +00002521 };
2522
2523 ///
2524 /// TODO: Add the implementation for other specialized builders here.
2525 ///
Samuel Antao64e965e2016-09-30 15:34:19 +00002526
2527 /// Specialized builders being used by this offloading action builder.
2528 SmallVector<DeviceActionBuilder *, 4> SpecializedBuilders;
2529
Samuel Antao69d6f312016-10-27 17:50:43 +00002530 /// Flag set to true if all valid builders allow file bundling/unbundling.
2531 bool CanUseBundler;
2532
Samuel Antao64e965e2016-09-30 15:34:19 +00002533public:
2534 OffloadingActionBuilder(Compilation &C, DerivedArgList &Args,
2535 const Driver::InputList &Inputs)
Samuel Antao10e905c2016-10-27 01:08:58 +00002536 : C(C) {
Samuel Antao64e965e2016-09-30 15:34:19 +00002537 // Create a specialized builder for each device toolchain.
2538
2539 IsValid = true;
2540
2541 // Create a specialized builder for CUDA.
2542 SpecializedBuilders.push_back(new CudaActionBuilder(C, Args, Inputs));
2543
Samuel Antao28c4f182016-10-27 17:08:03 +00002544 // Create a specialized builder for OpenMP.
2545 SpecializedBuilders.push_back(new OpenMPActionBuilder(C, Args, Inputs));
2546
Samuel Antao64e965e2016-09-30 15:34:19 +00002547 //
2548 // TODO: Build other specialized builders here.
2549 //
2550
Samuel Antao69d6f312016-10-27 17:50:43 +00002551 // Initialize all the builders, keeping track of errors. If all valid
2552 // builders agree that we can use bundling, set the flag to true.
2553 unsigned ValidBuilders = 0u;
2554 unsigned ValidBuildersSupportingBundling = 0u;
2555 for (auto *SB : SpecializedBuilders) {
Samuel Antao64e965e2016-09-30 15:34:19 +00002556 IsValid = IsValid && !SB->initialize();
Samuel Antao69d6f312016-10-27 17:50:43 +00002557
2558 // Update the counters if the builder is valid.
2559 if (SB->isValid()) {
2560 ++ValidBuilders;
2561 if (SB->canUseBundlerUnbundler())
2562 ++ValidBuildersSupportingBundling;
2563 }
2564 }
2565 CanUseBundler =
2566 ValidBuilders && ValidBuilders == ValidBuildersSupportingBundling;
Artem Belevichf981e30b2016-08-02 22:37:47 +00002567 }
Justin Lebardc3c5042016-04-19 02:27:07 +00002568
Samuel Antao64e965e2016-09-30 15:34:19 +00002569 ~OffloadingActionBuilder() {
2570 for (auto *SB : SpecializedBuilders)
2571 delete SB;
Samuel Antaod06239d2016-07-15 23:13:27 +00002572 }
Artem Belevich0ff05cd2015-07-13 23:27:56 +00002573
Samuel Antao64e965e2016-09-30 15:34:19 +00002574 /// Generate an action that adds device dependences (if any) to a host action.
2575 /// If no device dependence actions exist, just return the host action \a
2576 /// HostAction. If an error is found or if no builder requires the host action
2577 /// to be generated, return nullptr.
2578 Action *
2579 addDeviceDependencesToHostAction(Action *HostAction, const Arg *InputArg,
2580 phases::ID CurPhase, phases::ID FinalPhase,
2581 DeviceActionBuilder::PhasesTy &Phases) {
2582 if (!IsValid)
2583 return nullptr;
Justin Lebar7bf77982016-01-11 23:27:13 +00002584
Samuel Antao64e965e2016-09-30 15:34:19 +00002585 if (SpecializedBuilders.empty())
2586 return HostAction;
2587
2588 assert(HostAction && "Invalid host action!");
2589
2590 OffloadAction::DeviceDependences DDeps;
2591 // Check if all the programming models agree we should not emit the host
2592 // action. Also, keep track of the offloading kinds employed.
2593 auto &OffloadKind = InputArgToOffloadKindMap[InputArg];
2594 unsigned InactiveBuilders = 0u;
2595 unsigned IgnoringBuilders = 0u;
2596 for (auto *SB : SpecializedBuilders) {
2597 if (!SB->isValid()) {
2598 ++InactiveBuilders;
2599 continue;
2600 }
2601
Samuel Antao28c4f182016-10-27 17:08:03 +00002602 auto RetCode =
2603 SB->getDeviceDependences(DDeps, CurPhase, FinalPhase, Phases);
Samuel Antao64e965e2016-09-30 15:34:19 +00002604
2605 // If the builder explicitly says the host action should be ignored,
2606 // we need to increment the variable that tracks the builders that request
2607 // the host object to be ignored.
2608 if (RetCode == DeviceActionBuilder::ABRT_Ignore_Host)
2609 ++IgnoringBuilders;
2610
2611 // Unless the builder was inactive for this action, we have to record the
2612 // offload kind because the host will have to use it.
2613 if (RetCode != DeviceActionBuilder::ABRT_Inactive)
2614 OffloadKind |= SB->getAssociatedOffloadKind();
2615 }
2616
2617 // If all builders agree that the host object should be ignored, just return
2618 // nullptr.
2619 if (IgnoringBuilders &&
2620 SpecializedBuilders.size() == (InactiveBuilders + IgnoringBuilders))
2621 return nullptr;
2622
2623 if (DDeps.getActions().empty())
2624 return HostAction;
2625
2626 // We have dependences we need to bundle together. We use an offload action
2627 // for that.
2628 OffloadAction::HostDependence HDep(
2629 *HostAction, *C.getSingleOffloadToolChain<Action::OFK_Host>(),
2630 /*BoundArch=*/nullptr, DDeps);
2631 return C.MakeAction<OffloadAction>(HDep, DDeps);
Artem Belevich0ff05cd2015-07-13 23:27:56 +00002632 }
2633
Samuel Antao64e965e2016-09-30 15:34:19 +00002634 /// Generate an action that adds a host dependence to a device action. The
2635 /// results will be kept in this action builder. Return true if an error was
2636 /// found.
Samuel Antaofab4f372016-10-27 18:00:51 +00002637 bool addHostDependenceToDeviceActions(Action *&HostAction,
Samuel Antao64e965e2016-09-30 15:34:19 +00002638 const Arg *InputArg) {
2639 if (!IsValid)
2640 return true;
Artem Belevich0ff05cd2015-07-13 23:27:56 +00002641
Samuel Antaofab4f372016-10-27 18:00:51 +00002642 // If we are supporting bundling/unbundling and the current action is an
2643 // input action of non-source file, we replace the host action by the
2644 // unbundling action. The bundler tool has the logic to detect if an input
2645 // is a bundle or not and if the input is not a bundle it assumes it is a
2646 // host file. Therefore it is safe to create an unbundling action even if
2647 // the input is not a bundle.
2648 if (CanUseBundler && isa<InputAction>(HostAction) &&
2649 InputArg->getOption().getKind() == llvm::opt::Option::InputClass &&
2650 !types::isSrcFile(HostAction->getType())) {
2651 auto UnbundlingHostAction =
2652 C.MakeAction<OffloadUnbundlingJobAction>(HostAction);
2653 UnbundlingHostAction->registerDependentActionInfo(
2654 C.getSingleOffloadToolChain<Action::OFK_Host>(),
2655 /*BoundArch=*/StringRef(), Action::OFK_Host);
2656 HostAction = UnbundlingHostAction;
2657 }
2658
Samuel Antao64e965e2016-09-30 15:34:19 +00002659 assert(HostAction && "Invalid host action!");
Artem Belevich0ff05cd2015-07-13 23:27:56 +00002660
Samuel Antao64e965e2016-09-30 15:34:19 +00002661 // Register the offload kinds that are used.
2662 auto &OffloadKind = InputArgToOffloadKindMap[InputArg];
2663 for (auto *SB : SpecializedBuilders) {
2664 if (!SB->isValid())
2665 continue;
Artem Belevich0ff05cd2015-07-13 23:27:56 +00002666
Samuel Antao64e965e2016-09-30 15:34:19 +00002667 auto RetCode = SB->addDeviceDepences(HostAction);
Artem Belevich0ff05cd2015-07-13 23:27:56 +00002668
Samuel Antao64e965e2016-09-30 15:34:19 +00002669 // Host dependences for device actions are not compatible with that same
2670 // action being ignored.
2671 assert(RetCode != DeviceActionBuilder::ABRT_Ignore_Host &&
2672 "Host dependence not expected to be ignored.!");
Samuel Antaod06239d2016-07-15 23:13:27 +00002673
Samuel Antao64e965e2016-09-30 15:34:19 +00002674 // Unless the builder was inactive for this action, we have to record the
2675 // offload kind because the host will have to use it.
2676 if (RetCode != DeviceActionBuilder::ABRT_Inactive)
2677 OffloadKind |= SB->getAssociatedOffloadKind();
2678 }
Artem Belevich0ff05cd2015-07-13 23:27:56 +00002679
Samuel Antao64e965e2016-09-30 15:34:19 +00002680 return false;
2681 }
2682
Samuel Antao69d6f312016-10-27 17:50:43 +00002683 /// Add the offloading top level actions to the provided action list. This
2684 /// function can replace the host action by a bundling action if the
2685 /// programming models allow it.
Samuel Antao64e965e2016-09-30 15:34:19 +00002686 bool appendTopLevelActions(ActionList &AL, Action *HostAction,
2687 const Arg *InputArg) {
Samuel Antao69d6f312016-10-27 17:50:43 +00002688 // Get the device actions to be appended.
2689 ActionList OffloadAL;
Samuel Antao64e965e2016-09-30 15:34:19 +00002690 for (auto *SB : SpecializedBuilders) {
2691 if (!SB->isValid())
2692 continue;
Samuel Antao69d6f312016-10-27 17:50:43 +00002693 SB->appendTopLevelActions(OffloadAL);
Samuel Antao64e965e2016-09-30 15:34:19 +00002694 }
2695
Samuel Antao69d6f312016-10-27 17:50:43 +00002696 // If we can use the bundler, replace the host action by the bundling one in
2697 // the resulting list. Otherwise, just append the device actions.
2698 if (CanUseBundler && !OffloadAL.empty()) {
2699 // Add the host action to the list in order to create the bundling action.
2700 OffloadAL.push_back(HostAction);
2701
2702 // We expect that the host action was just appended to the action list
2703 // before this method was called.
2704 assert(HostAction == AL.back() && "Host action not in the list??");
2705 HostAction = C.MakeAction<OffloadBundlingJobAction>(OffloadAL);
2706 AL.back() = HostAction;
2707 } else
2708 AL.append(OffloadAL.begin(), OffloadAL.end());
2709
Samuel Antao64e965e2016-09-30 15:34:19 +00002710 // Propagate to the current host action (if any) the offload information
2711 // associated with the current input.
2712 if (HostAction)
2713 HostAction->propagateHostOffloadInfo(InputArgToOffloadKindMap[InputArg],
2714 /*BoundArch=*/nullptr);
Samuel Antao64e965e2016-09-30 15:34:19 +00002715 return false;
Artem Belevich0ff05cd2015-07-13 23:27:56 +00002716 }
Artem Belevich5bde4e02015-07-20 20:02:54 +00002717
Samuel Antao64e965e2016-09-30 15:34:19 +00002718 /// Processes the host linker action. This currently consists of replacing it
2719 /// with an offload action if there are device link objects and propagate to
2720 /// the host action all the offload kinds used in the current compilation. The
2721 /// resulting action is returned.
2722 Action *processHostLinkAction(Action *HostAction) {
2723 // Add all the dependences from the device linking actions.
2724 OffloadAction::DeviceDependences DDeps;
2725 for (auto *SB : SpecializedBuilders) {
2726 if (!SB->isValid())
2727 continue;
Justin Lebar21e5d4f2016-01-14 21:41:27 +00002728
Samuel Antao64e965e2016-09-30 15:34:19 +00002729 SB->appendLinkDependences(DDeps);
Justin Lebar21e5d4f2016-01-14 21:41:27 +00002730 }
Samuel Antaod06239d2016-07-15 23:13:27 +00002731
Samuel Antao64e965e2016-09-30 15:34:19 +00002732 // Calculate all the offload kinds used in the current compilation.
2733 unsigned ActiveOffloadKinds = 0u;
2734 for (auto &I : InputArgToOffloadKindMap)
2735 ActiveOffloadKinds |= I.second;
2736
2737 // If we don't have device dependencies, we don't have to create an offload
2738 // action.
2739 if (DDeps.getActions().empty()) {
2740 // Propagate all the active kinds to host action. Given that it is a link
2741 // action it is assumed to depend on all actions generated so far.
2742 HostAction->propagateHostOffloadInfo(ActiveOffloadKinds,
2743 /*BoundArch=*/nullptr);
2744 return HostAction;
2745 }
2746
2747 // Create the offload action with all dependences. When an offload action
2748 // is created the kinds are propagated to the host action, so we don't have
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00002749 // to do that explicitly here.
Samuel Antao64e965e2016-09-30 15:34:19 +00002750 OffloadAction::HostDependence HDep(
2751 *HostAction, *C.getSingleOffloadToolChain<Action::OFK_Host>(),
2752 /*BoundArch*/ nullptr, ActiveOffloadKinds);
2753 return C.MakeAction<OffloadAction>(HDep, DDeps);
2754 }
2755};
2756} // anonymous namespace.
Artem Belevich0ff05cd2015-07-13 23:27:56 +00002757
Justin Lebar0f3474c2016-02-11 02:00:50 +00002758void Driver::BuildActions(Compilation &C, DerivedArgList &Args,
2759 const InputList &Inputs, ActionList &Actions) const {
Chad Rosierecdede82011-08-12 22:08:57 +00002760 llvm::PrettyStackTraceString CrashInfo("Building compilation actions");
Joerg Sonnenbergerb86f5f42011-03-06 23:31:01 +00002761
Daniel Dunbar34c41872009-03-13 00:17:48 +00002762 if (!SuppressMissingInputWarning && Inputs.empty()) {
Daniel Dunbarbfeec742009-03-12 23:55:14 +00002763 Diag(clang::diag::err_drv_no_input_files);
2764 return;
2765 }
2766
Chad Rosier7742b5d2011-07-27 23:36:45 +00002767 Arg *FinalPhaseArg;
2768 phases::ID FinalPhase = getFinalPhase(Args, &FinalPhaseArg);
Daniel Dunbarbfeec742009-03-12 23:55:14 +00002769
Bob Haarmanaaf51912017-02-27 19:40:19 +00002770 if (FinalPhase == phases::Link) {
2771 if (Args.hasArg(options::OPT_emit_llvm))
2772 Diag(clang::diag::err_drv_emit_llvm_link);
2773 if (IsCLMode() && LTOMode != LTOK_None &&
2774 !Args.getLastArgValue(options::OPT_fuse_ld_EQ).equals_lower("lld"))
2775 Diag(clang::diag::err_drv_lto_without_lld);
Rafael Espindolae8025642013-08-25 14:27:09 +00002776 }
2777
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00002778 // Reject -Z* at the top level, these options should never have been exposed
2779 // by gcc.
Daniel Dunbardd765242009-03-26 16:12:09 +00002780 if (Arg *A = Args.getLastArg(options::OPT_Z_Joined))
Daniel Dunbar0e759942009-03-20 06:14:23 +00002781 Diag(clang::diag::err_drv_use_of_Z_option) << A->getAsString(Args);
Daniel Dunbarbfeec742009-03-12 23:55:14 +00002782
Hans Wennborg13b7fe72013-08-12 23:26:25 +00002783 // Diagnose misuse of /Fo.
2784 if (Arg *A = Args.getLastArg(options::OPT__SLASH_Fo)) {
Hans Wennborg13b7fe72013-08-12 23:26:25 +00002785 StringRef V = A->getValue();
Hans Wennborg61647532014-11-17 19:16:36 +00002786 if (Inputs.size() > 1 && !V.empty() &&
2787 !llvm::sys::path::is_separator(V.back())) {
Hans Wennborg13b7fe72013-08-12 23:26:25 +00002788 // Check whether /Fo tries to name an output file for multiple inputs.
Hans Wennborg9c1659b2013-10-18 22:49:04 +00002789 Diag(clang::diag::err_drv_out_file_argument_with_multiple_sources)
Douglas Katzmana67e50c2015-06-26 15:47:46 +00002790 << A->getSpelling() << V;
Hans Wennborg13b7fe72013-08-12 23:26:25 +00002791 Args.eraseArg(options::OPT__SLASH_Fo);
2792 }
2793 }
2794
Hans Wennborg9c1659b2013-10-18 22:49:04 +00002795 // Diagnose misuse of /Fa.
2796 if (Arg *A = Args.getLastArg(options::OPT__SLASH_Fa)) {
2797 StringRef V = A->getValue();
Hans Wennborg61647532014-11-17 19:16:36 +00002798 if (Inputs.size() > 1 && !V.empty() &&
2799 !llvm::sys::path::is_separator(V.back())) {
Hans Wennborg9c1659b2013-10-18 22:49:04 +00002800 // Check whether /Fa tries to name an asm file for multiple inputs.
2801 Diag(clang::diag::err_drv_out_file_argument_with_multiple_sources)
Douglas Katzmana67e50c2015-06-26 15:47:46 +00002802 << A->getSpelling() << V;
Hans Wennborg9c1659b2013-10-18 22:49:04 +00002803 Args.eraseArg(options::OPT__SLASH_Fa);
2804 }
2805 }
2806
Ehsan Akhgari81f36b72014-09-11 18:16:21 +00002807 // Diagnose misuse of /o.
2808 if (Arg *A = Args.getLastArg(options::OPT__SLASH_o)) {
2809 if (A->getValue()[0] == '\0') {
2810 // It has to have a value.
2811 Diag(clang::diag::err_drv_missing_argument) << A->getSpelling() << 1;
2812 Args.eraseArg(options::OPT__SLASH_o);
2813 }
2814 }
2815
Nico Weber2ca4be92016-03-01 23:16:44 +00002816 // Diagnose unsupported forms of /Yc /Yu. Ignore /Yc/Yu for now if:
2817 // * no filename after it
2818 // * both /Yc and /Yu passed but with different filenames
2819 // * corresponding file not also passed as /FI
2820 Arg *YcArg = Args.getLastArg(options::OPT__SLASH_Yc);
2821 Arg *YuArg = Args.getLastArg(options::OPT__SLASH_Yu);
2822 if (YcArg && YcArg->getValue()[0] == '\0') {
2823 Diag(clang::diag::warn_drv_ycyu_no_arg_clang_cl) << YcArg->getSpelling();
2824 Args.eraseArg(options::OPT__SLASH_Yc);
2825 YcArg = nullptr;
2826 }
2827 if (YuArg && YuArg->getValue()[0] == '\0') {
2828 Diag(clang::diag::warn_drv_ycyu_no_arg_clang_cl) << YuArg->getSpelling();
2829 Args.eraseArg(options::OPT__SLASH_Yu);
2830 YuArg = nullptr;
2831 }
2832 if (YcArg && YuArg && strcmp(YcArg->getValue(), YuArg->getValue()) != 0) {
2833 Diag(clang::diag::warn_drv_ycyu_different_arg_clang_cl);
2834 Args.eraseArg(options::OPT__SLASH_Yc);
2835 Args.eraseArg(options::OPT__SLASH_Yu);
2836 YcArg = YuArg = nullptr;
2837 }
2838 if (YcArg || YuArg) {
2839 StringRef Val = YcArg ? YcArg->getValue() : YuArg->getValue();
2840 bool FoundMatchingInclude = false;
2841 for (const Arg *Inc : Args.filtered(options::OPT_include)) {
2842 // FIXME: Do case-insensitive matching and consider / and \ as equal.
2843 if (Inc->getValue() == Val)
2844 FoundMatchingInclude = true;
2845 }
2846 if (!FoundMatchingInclude) {
2847 Diag(clang::diag::warn_drv_ycyu_no_fi_arg_clang_cl)
2848 << (YcArg ? YcArg : YuArg)->getSpelling();
2849 Args.eraseArg(options::OPT__SLASH_Yc);
2850 Args.eraseArg(options::OPT__SLASH_Yu);
2851 YcArg = YuArg = nullptr;
2852 }
2853 }
2854 if (YcArg && Inputs.size() > 1) {
2855 Diag(clang::diag::warn_drv_yc_multiple_inputs_clang_cl);
2856 Args.eraseArg(options::OPT__SLASH_Yc);
2857 YcArg = nullptr;
2858 }
2859 if (Args.hasArg(options::OPT__SLASH_Y_)) {
2860 // /Y- disables all pch handling. Rather than check for it everywhere,
2861 // just remove clang-cl pch-related flags here.
2862 Args.eraseArg(options::OPT__SLASH_Fp);
2863 Args.eraseArg(options::OPT__SLASH_Yc);
2864 Args.eraseArg(options::OPT__SLASH_Yu);
2865 YcArg = YuArg = nullptr;
2866 }
Nico Weber2ca4be92016-03-01 23:16:44 +00002867
Samuel Antao64e965e2016-09-30 15:34:19 +00002868 // Builder to be used to build offloading actions.
2869 OffloadingActionBuilder OffloadBuilder(C, Args, Inputs);
Samuel Antaod06239d2016-07-15 23:13:27 +00002870
Daniel Dunbar65229332009-03-13 11:38:42 +00002871 // Construct the actions to perform.
2872 ActionList LinkerInputs;
Alp Toker965f8822013-11-27 05:22:15 +00002873
Matthew Curtis7ab8b2b2013-03-07 12:32:26 +00002874 llvm::SmallVector<phases::ID, phases::MaxNumberOfPhases> PL;
Artem Belevich5bde4e02015-07-20 20:02:54 +00002875 for (auto &I : Inputs) {
2876 types::ID InputType = I.first;
2877 const Arg *InputArg = I.second;
Daniel Dunbar65229332009-03-13 11:38:42 +00002878
Matthew Curtis7ab8b2b2013-03-07 12:32:26 +00002879 PL.clear();
2880 types::getCompilationPhases(InputType, PL);
Daniel Dunbar65229332009-03-13 11:38:42 +00002881
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00002882 // If the first step comes after the final phase we are doing as part of
2883 // this compilation, warn the user about it.
Matthew Curtis7ab8b2b2013-03-07 12:32:26 +00002884 phases::ID InitialPhase = PL[0];
Daniel Dunbar65229332009-03-13 11:38:42 +00002885 if (InitialPhase > FinalPhase) {
Daniel Dunbaradc5c7c2009-03-19 07:57:08 +00002886 // Claim here to avoid the more general unused warning.
2887 InputArg->claim();
Daniel Dunbar07806ca2009-09-17 04:13:26 +00002888
Daniel Dunbar2db3e732011-04-20 15:44:48 +00002889 // Suppress all unused style warnings with -Qunused-arguments
2890 if (Args.hasArg(options::OPT_Qunused_arguments))
2891 continue;
2892
Richard Smith403f76e2012-08-06 04:09:06 +00002893 // Special case when final phase determined by binary name, rather than
2894 // by a command-line argument with a corresponding Arg.
Hans Wennborg70850d82013-07-18 20:29:38 +00002895 if (CCCIsCPP())
Richard Smith403f76e2012-08-06 04:09:06 +00002896 Diag(clang::diag::warn_drv_input_file_unused_by_cpp)
Douglas Katzmana67e50c2015-06-26 15:47:46 +00002897 << InputArg->getAsString(Args) << getPhaseName(InitialPhase);
Daniel Dunbar07806ca2009-09-17 04:13:26 +00002898 // Special case '-E' warning on a previously preprocessed file to make
2899 // more sense.
Richard Smith403f76e2012-08-06 04:09:06 +00002900 else if (InitialPhase == phases::Compile &&
2901 FinalPhase == phases::Preprocess &&
2902 getPreprocessedType(InputType) == types::TY_INVALID)
Daniel Dunbar07806ca2009-09-17 04:13:26 +00002903 Diag(clang::diag::warn_drv_preprocessed_input_file_unused)
Douglas Katzmana67e50c2015-06-26 15:47:46 +00002904 << InputArg->getAsString(Args) << !!FinalPhaseArg
2905 << (FinalPhaseArg ? FinalPhaseArg->getOption().getName() : "");
Daniel Dunbar07806ca2009-09-17 04:13:26 +00002906 else
2907 Diag(clang::diag::warn_drv_input_file_unused)
Douglas Katzmana67e50c2015-06-26 15:47:46 +00002908 << InputArg->getAsString(Args) << getPhaseName(InitialPhase)
2909 << !!FinalPhaseArg
2910 << (FinalPhaseArg ? FinalPhaseArg->getOption().getName() : "");
Daniel Dunbar65229332009-03-13 11:38:42 +00002911 continue;
2912 }
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00002913
Nico Weberad2d8f32016-04-21 19:59:10 +00002914 if (YcArg) {
2915 // Add a separate precompile phase for the compile phase.
2916 if (FinalPhase >= phases::Compile) {
Richard Smith8cd452d2016-08-30 18:55:16 +00002917 const types::ID HeaderType = lookupHeaderTypeForSourceType(InputType);
Nico Weberad2d8f32016-04-21 19:59:10 +00002918 llvm::SmallVector<phases::ID, phases::MaxNumberOfPhases> PCHPL;
Richard Smith8cd452d2016-08-30 18:55:16 +00002919 types::getCompilationPhases(HeaderType, PCHPL);
David Blaikie0aaa7622017-01-13 17:34:15 +00002920 Arg *PchInputArg = MakeInputArg(Args, *Opts, YcArg->getValue());
Nico Weberad2d8f32016-04-21 19:59:10 +00002921
2922 // Build the pipeline for the pch file.
Richard Smith8cd452d2016-08-30 18:55:16 +00002923 Action *ClangClPch =
2924 C.MakeAction<InputAction>(*PchInputArg, HeaderType);
Nico Weberad2d8f32016-04-21 19:59:10 +00002925 for (phases::ID Phase : PCHPL)
2926 ClangClPch = ConstructPhaseAction(C, Args, Phase, ClangClPch);
2927 assert(ClangClPch);
2928 Actions.push_back(ClangClPch);
2929 // The driver currently exits after the first failed command. This
2930 // relies on that behavior, to make sure if the pch generation fails,
2931 // the main compilation won't run.
2932 }
2933 }
2934
Daniel Dunbar65229332009-03-13 11:38:42 +00002935 // Build the pipeline for this file.
Justin Lebar41094612016-01-11 23:07:27 +00002936 Action *Current = C.MakeAction<InputAction>(*InputArg, InputType);
Samuel Antao64e965e2016-09-30 15:34:19 +00002937
2938 // Use the current host action in any of the offloading actions, if
2939 // required.
2940 if (OffloadBuilder.addHostDependenceToDeviceActions(Current, InputArg))
2941 break;
2942
Douglas Katzmana67e50c2015-06-26 15:47:46 +00002943 for (SmallVectorImpl<phases::ID>::iterator i = PL.begin(), e = PL.end();
2944 i != e; ++i) {
Matthew Curtis7ab8b2b2013-03-07 12:32:26 +00002945 phases::ID Phase = *i;
Daniel Dunbar65229332009-03-13 11:38:42 +00002946
2947 // We are done if this step is past what the user requested.
2948 if (Phase > FinalPhase)
2949 break;
2950
Samuel Antao64e965e2016-09-30 15:34:19 +00002951 // Add any offload action the host action depends on.
2952 Current = OffloadBuilder.addDeviceDependencesToHostAction(
2953 Current, InputArg, Phase, FinalPhase, PL);
2954 if (!Current)
2955 break;
2956
Daniel Dunbar65229332009-03-13 11:38:42 +00002957 // Queue linker inputs.
2958 if (Phase == phases::Link) {
Matthew Curtis7ab8b2b2013-03-07 12:32:26 +00002959 assert((i + 1) == e && "linking must be final compilation step.");
Justin Lebar41094612016-01-11 23:07:27 +00002960 LinkerInputs.push_back(Current);
2961 Current = nullptr;
Daniel Dunbar65229332009-03-13 11:38:42 +00002962 break;
2963 }
2964
Samuel Antao64e965e2016-09-30 15:34:19 +00002965 // Otherwise construct the appropriate action.
2966 auto *NewCurrent = ConstructPhaseAction(C, Args, Phase, Current);
2967
2968 // We didn't create a new action, so we will just move to the next phase.
2969 if (NewCurrent == Current)
Daniel Dunbar13864952009-03-24 20:17:30 +00002970 continue;
2971
Samuel Antao64e965e2016-09-30 15:34:19 +00002972 Current = NewCurrent;
Artem Belevich0ff05cd2015-07-13 23:27:56 +00002973
Samuel Antao64e965e2016-09-30 15:34:19 +00002974 // Use the current host action in any of the offloading actions, if
2975 // required.
2976 if (OffloadBuilder.addHostDependenceToDeviceActions(Current, InputArg))
2977 break;
Artem Belevich0ff05cd2015-07-13 23:27:56 +00002978
Daniel Dunbar65229332009-03-13 11:38:42 +00002979 if (Current->getType() == types::TY_Nothing)
2980 break;
2981 }
2982
Samuel Antao64e965e2016-09-30 15:34:19 +00002983 // If we ended with something, add to the output list.
2984 if (Current)
Justin Lebar41094612016-01-11 23:07:27 +00002985 Actions.push_back(Current);
Samuel Antao64e965e2016-09-30 15:34:19 +00002986
2987 // Add any top level actions generated for offloading.
2988 OffloadBuilder.appendTopLevelActions(Actions, Current, InputArg);
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00002989 }
Daniel Dunbar65229332009-03-13 11:38:42 +00002990
Samuel Antao64e965e2016-09-30 15:34:19 +00002991 // Add a link action if necessary.
Samuel Antaod06239d2016-07-15 23:13:27 +00002992 if (!LinkerInputs.empty()) {
Samuel Antao64e965e2016-09-30 15:34:19 +00002993 Action *LA = C.MakeAction<LinkJobAction>(LinkerInputs, types::TY_Image);
2994 LA = OffloadBuilder.processHostLinkAction(LA);
2995 Actions.push_back(LA);
Samuel Antaod06239d2016-07-15 23:13:27 +00002996 }
Daniel Dunbarc7a67b72009-12-22 23:19:32 +00002997
2998 // If we are linking, claim any options which are obviously only used for
2999 // compilation.
Hans Wennborga8ef14f2013-09-17 00:03:41 +00003000 if (FinalPhase == phases::Link && PL.size() == 1) {
Daniel Dunbarc7a67b72009-12-22 23:19:32 +00003001 Args.ClaimAllArgs(options::OPT_CompileOnly_Group);
Hans Wennborga8ef14f2013-09-17 00:03:41 +00003002 Args.ClaimAllArgs(options::OPT_cl_compile_Group);
3003 }
3004
3005 // Claim ignored clang-cl options.
3006 Args.ClaimAllArgs(options::OPT_cl_ignored_Group);
Artem Belevichbaae0932015-07-28 21:01:30 +00003007
Justin Lebardc3c5042016-04-19 02:27:07 +00003008 // Claim --cuda-host-only and --cuda-compile-host-device, which may be passed
3009 // to non-CUDA compilations and should not trigger warnings there.
Artem Belevichbaae0932015-07-28 21:01:30 +00003010 Args.ClaimAllArgs(options::OPT_cuda_host_only);
Justin Lebardc3c5042016-04-19 02:27:07 +00003011 Args.ClaimAllArgs(options::OPT_cuda_compile_host_device);
Daniel Dunbar65229332009-03-13 11:38:42 +00003012}
3013
Artem Belevichecb178b2018-03-21 22:22:59 +00003014Action *Driver::ConstructPhaseAction(
3015 Compilation &C, const ArgList &Args, phases::ID Phase, Action *Input,
3016 Action::OffloadKind TargetDeviceOffloadKind) const {
Daniel Dunbar2608c542009-03-18 01:38:48 +00003017 llvm::PrettyStackTraceString CrashInfo("Constructing phase actions");
Samuel Antao64e965e2016-09-30 15:34:19 +00003018
3019 // Some types skip the assembler phase (e.g., llvm-bc), but we can't
3020 // encode this in the steps because the intermediate type depends on
3021 // arguments. Just special case here.
3022 if (Phase == phases::Assemble && Input->getType() != types::TY_PP_Asm)
3023 return Input;
3024
Daniel Dunbar65229332009-03-13 11:38:42 +00003025 // Build the appropriate action.
3026 switch (Phase) {
Douglas Katzmana67e50c2015-06-26 15:47:46 +00003027 case phases::Link:
3028 llvm_unreachable("link action invalid here.");
Daniel Dunbar65229332009-03-13 11:38:42 +00003029 case phases::Preprocess: {
Daniel Dunbard67a3222009-03-30 06:36:42 +00003030 types::ID OutputTy;
3031 // -{M, MM} alter the output type.
Daniel Dunbar86aed7d2010-12-08 21:33:40 +00003032 if (Args.hasArg(options::OPT_M, options::OPT_MM)) {
Daniel Dunbard67a3222009-03-30 06:36:42 +00003033 OutputTy = types::TY_Dependencies;
3034 } else {
David Blaikie5d577a22012-06-29 22:03:56 +00003035 OutputTy = Input->getType();
3036 if (!Args.hasFlag(options::OPT_frewrite_includes,
Justin Bognerce8245b2014-06-24 08:01:01 +00003037 options::OPT_fno_rewrite_includes, false) &&
Richard Smith86a3ef52017-06-09 21:24:02 +00003038 !Args.hasFlag(options::OPT_frewrite_imports,
3039 options::OPT_fno_rewrite_imports, false) &&
Justin Bognerce8245b2014-06-24 08:01:01 +00003040 !CCGenDiagnostics)
David Blaikie5d577a22012-06-29 22:03:56 +00003041 OutputTy = types::getPreprocessedType(OutputTy);
Daniel Dunbard67a3222009-03-30 06:36:42 +00003042 assert(OutputTy != types::TY_INVALID &&
3043 "Cannot preprocess this input type!");
3044 }
Justin Lebar41094612016-01-11 23:07:27 +00003045 return C.MakeAction<PreprocessJobAction>(Input, OutputTy);
Daniel Dunbar65229332009-03-13 11:38:42 +00003046 }
Aaron Ballman1f10cc52012-07-31 01:21:00 +00003047 case phases::Precompile: {
Richard Smithdd4ad3d2016-08-30 19:06:26 +00003048 types::ID OutputTy = getPrecompiledType(Input->getType());
3049 assert(OutputTy != types::TY_INVALID &&
3050 "Cannot precompile this input type!");
Aaron Ballman1f10cc52012-07-31 01:21:00 +00003051 if (Args.hasArg(options::OPT_fsyntax_only)) {
3052 // Syntax checks should not emit a PCH file
3053 OutputTy = types::TY_Nothing;
3054 }
Justin Lebar41094612016-01-11 23:07:27 +00003055 return C.MakeAction<PrecompileJobAction>(Input, OutputTy);
Aaron Ballman1f10cc52012-07-31 01:21:00 +00003056 }
Daniel Dunbar65229332009-03-13 11:38:42 +00003057 case phases::Compile: {
David Blaikie486f4402014-08-29 07:25:23 +00003058 if (Args.hasArg(options::OPT_fsyntax_only))
Justin Lebar41094612016-01-11 23:07:27 +00003059 return C.MakeAction<CompileJobAction>(Input, types::TY_Nothing);
David Blaikie486f4402014-08-29 07:25:23 +00003060 if (Args.hasArg(options::OPT_rewrite_objc))
Justin Lebar41094612016-01-11 23:07:27 +00003061 return C.MakeAction<CompileJobAction>(Input, types::TY_RewrittenObjC);
David Blaikie486f4402014-08-29 07:25:23 +00003062 if (Args.hasArg(options::OPT_rewrite_legacy_objc))
Justin Lebar41094612016-01-11 23:07:27 +00003063 return C.MakeAction<CompileJobAction>(Input,
3064 types::TY_RewrittenLegacyObjC);
David Blaikie486f4402014-08-29 07:25:23 +00003065 if (Args.hasArg(options::OPT__analyze, options::OPT__analyze_auto))
Justin Lebar41094612016-01-11 23:07:27 +00003066 return C.MakeAction<AnalyzeJobAction>(Input, types::TY_Plist);
David Blaikie486f4402014-08-29 07:25:23 +00003067 if (Args.hasArg(options::OPT__migrate))
Justin Lebar41094612016-01-11 23:07:27 +00003068 return C.MakeAction<MigrateJobAction>(Input, types::TY_Remap);
David Blaikie486f4402014-08-29 07:25:23 +00003069 if (Args.hasArg(options::OPT_emit_ast))
Justin Lebar41094612016-01-11 23:07:27 +00003070 return C.MakeAction<CompileJobAction>(Input, types::TY_AST);
David Blaikie486f4402014-08-29 07:25:23 +00003071 if (Args.hasArg(options::OPT_module_file_info))
Justin Lebar41094612016-01-11 23:07:27 +00003072 return C.MakeAction<CompileJobAction>(Input, types::TY_ModuleFile);
David Blaikie486f4402014-08-29 07:25:23 +00003073 if (Args.hasArg(options::OPT_verify_pch))
Justin Lebar41094612016-01-11 23:07:27 +00003074 return C.MakeAction<VerifyPCHJobAction>(Input, types::TY_Nothing);
3075 return C.MakeAction<CompileJobAction>(Input, types::TY_LLVM_BC);
Bob Wilson23a55f12014-12-21 07:00:00 +00003076 }
3077 case phases::Backend: {
Artem Belevichecb178b2018-03-21 22:22:59 +00003078 if (isUsingLTO() && TargetDeviceOffloadKind == Action::OFK_None) {
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00003079 types::ID Output =
Douglas Katzmana67e50c2015-06-26 15:47:46 +00003080 Args.hasArg(options::OPT_S) ? types::TY_LTO_IR : types::TY_LTO_BC;
Justin Lebar41094612016-01-11 23:07:27 +00003081 return C.MakeAction<BackendJobAction>(Input, Output);
David Blaikie486f4402014-08-29 07:25:23 +00003082 }
3083 if (Args.hasArg(options::OPT_emit_llvm)) {
Shuxin Yang4b3c7ff2013-08-23 21:34:57 +00003084 types::ID Output =
Douglas Katzmana67e50c2015-06-26 15:47:46 +00003085 Args.hasArg(options::OPT_S) ? types::TY_LLVM_IR : types::TY_LLVM_BC;
Justin Lebar41094612016-01-11 23:07:27 +00003086 return C.MakeAction<BackendJobAction>(Input, Output);
Daniel Dunbar65229332009-03-13 11:38:42 +00003087 }
Justin Lebar41094612016-01-11 23:07:27 +00003088 return C.MakeAction<BackendJobAction>(Input, types::TY_PP_Asm);
Daniel Dunbar65229332009-03-13 11:38:42 +00003089 }
3090 case phases::Assemble:
Justin Lebar21e5d4f2016-01-14 21:41:27 +00003091 return C.MakeAction<AssembleJobAction>(std::move(Input), types::TY_Object);
Daniel Dunbar65229332009-03-13 11:38:42 +00003092 }
3093
David Blaikie83d382b2011-09-23 05:06:16 +00003094 llvm_unreachable("invalid phase in ConstructPhaseAction");
Daniel Dunbar1688f1a2009-03-12 07:58:46 +00003095}
3096
Daniel Dunbarf0eddb82009-03-18 02:55:38 +00003097void Driver::BuildJobs(Compilation &C) const {
Daniel Dunbar2608c542009-03-18 01:38:48 +00003098 llvm::PrettyStackTraceString CrashInfo("Building compilation jobs");
Daniel Dunbare75d8342009-03-16 06:56:51 +00003099
3100 Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o);
3101
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00003102 // It is an error to provide a -o option if we are making multiple output
3103 // files.
Daniel Dunbare75d8342009-03-16 06:56:51 +00003104 if (FinalOutput) {
3105 unsigned NumOutputs = 0;
Saleem Abdulrasoolda3f4e52014-12-29 21:02:47 +00003106 for (const Action *A : C.getActions())
3107 if (A->getType() != types::TY_Nothing)
Daniel Dunbare75d8342009-03-16 06:56:51 +00003108 ++NumOutputs;
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00003109
Daniel Dunbare75d8342009-03-16 06:56:51 +00003110 if (NumOutputs > 1) {
3111 Diag(clang::diag::err_drv_output_argument_with_multiple_files);
Craig Topper92fc2df2014-05-17 16:56:41 +00003112 FinalOutput = nullptr;
Daniel Dunbare75d8342009-03-16 06:56:51 +00003113 }
3114 }
3115
Chad Rosier35767232013-04-30 22:01:21 +00003116 // Collect the list of architectures.
3117 llvm::StringSet<> ArchNames;
Saleem Abdulrasool688b6bc2014-12-29 19:01:36 +00003118 if (C.getDefaultToolChain().getTriple().isOSBinFormatMachO())
3119 for (const Arg *A : C.getArgs())
Chad Rosier35767232013-04-30 22:01:21 +00003120 if (A->getOption().matches(options::OPT_arch))
3121 ArchNames.insert(A->getValue());
Chad Rosier35767232013-04-30 22:01:21 +00003122
Justin Lebarb44f6fe2016-01-14 21:41:21 +00003123 // Set of (Action, canonical ToolChain triple) pairs we've built jobs for.
3124 std::map<std::pair<const Action *, std::string>, InputInfo> CachedResults;
Saleem Abdulrasool688b6bc2014-12-29 19:01:36 +00003125 for (Action *A : C.getActions()) {
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00003126 // If we are linking an image for multiple archs then the linker wants
3127 // -arch_multiple and -final_output <final image name>. Unfortunately, this
3128 // doesn't fit in cleanly because we have to pass this information down.
Daniel Dunbare75d8342009-03-16 06:56:51 +00003129 //
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00003130 // FIXME: This is a hack; find a cleaner way to integrate this into the
3131 // process.
Craig Topper92fc2df2014-05-17 16:56:41 +00003132 const char *LinkingOutput = nullptr;
Daniel Dunbardd765242009-03-26 16:12:09 +00003133 if (isa<LipoJobAction>(A)) {
Daniel Dunbare75d8342009-03-16 06:56:51 +00003134 if (FinalOutput)
Richard Smithbd55daf2012-11-01 04:30:05 +00003135 LinkingOutput = FinalOutput->getValue();
Daniel Dunbare75d8342009-03-16 06:56:51 +00003136 else
Hans Wennborga7707222015-01-09 17:38:53 +00003137 LinkingOutput = getDefaultImageName();
Daniel Dunbare75d8342009-03-16 06:56:51 +00003138 }
3139
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00003140 BuildJobsForAction(C, A, &C.getDefaultToolChain(),
Mehdi Aminic50b1a22016-10-07 21:27:26 +00003141 /*BoundArch*/ StringRef(),
Daniel Dunbare75d8342009-03-16 06:56:51 +00003142 /*AtTopLevel*/ true,
Chad Rosier35767232013-04-30 22:01:21 +00003143 /*MultipleArchs*/ ArchNames.size() > 1,
Samuel Antaod06239d2016-07-15 23:13:27 +00003144 /*LinkingOutput*/ LinkingOutput, CachedResults,
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003145 /*TargetDeviceOffloadKind*/ Action::OFK_None);
Daniel Dunbare75d8342009-03-16 06:56:51 +00003146 }
Daniel Dunbar3ce436d2009-03-16 06:42:30 +00003147
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00003148 // If the user passed -Qunused-arguments or there were errors, don't warn
3149 // about any unused arguments.
Argyrios Kyrtzidis31448a42010-11-18 21:47:07 +00003150 if (Diags.hasErrorOccurred() ||
Daniel Dunbara3cfbe32009-04-07 19:04:18 +00003151 C.getArgs().hasArg(options::OPT_Qunused_arguments))
Daniel Dunbard175d972009-03-18 18:03:46 +00003152 return;
3153
Daniel Dunbar58399ae2009-03-29 22:24:54 +00003154 // Claim -### here.
Douglas Katzmana67e50c2015-06-26 15:47:46 +00003155 (void)C.getArgs().hasArg(options::OPT__HASH_HASH_HASH);
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00003156
Nico Weber47bf5052016-04-25 21:15:49 +00003157 // Claim --driver-mode, --rsp-quoting, it was handled earlier.
Douglas Katzmana67e50c2015-06-26 15:47:46 +00003158 (void)C.getArgs().hasArg(options::OPT_driver_mode);
Nico Weber47bf5052016-04-25 21:15:49 +00003159 (void)C.getArgs().hasArg(options::OPT_rsp_quoting);
Hans Wennborg70850d82013-07-18 20:29:38 +00003160
Saleem Abdulrasool688b6bc2014-12-29 19:01:36 +00003161 for (Arg *A : C.getArgs()) {
Daniel Dunbar3ce436d2009-03-16 06:42:30 +00003162 // FIXME: It would be nice to be able to send the argument to the
David Blaikie9c902b52011-09-25 23:23:43 +00003163 // DiagnosticsEngine, so that extra values, position, and so on could be
3164 // printed.
Daniel Dunbar90dd6f42009-04-04 00:52:26 +00003165 if (!A->isClaimed()) {
Michael J. Spencer66e2b202012-10-19 22:37:06 +00003166 if (A->getOption().hasFlag(options::NoArgumentUnused))
Daniel Dunbara3cfbe32009-04-07 19:04:18 +00003167 continue;
3168
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00003169 // Suppress the warning automatically if this is just a flag, and it is an
3170 // instance of an argument we already claimed.
Daniel Dunbar90dd6f42009-04-04 00:52:26 +00003171 const Option &Opt = A->getOption();
Michael J. Spencerad3ccc32012-08-20 21:41:17 +00003172 if (Opt.getKind() == Option::FlagClass) {
Daniel Dunbar90dd6f42009-04-04 00:52:26 +00003173 bool DuplicateClaimed = false;
3174
Sean Silva14facf32015-06-09 01:57:17 +00003175 for (const Arg *AA : C.getArgs().filtered(&Opt)) {
3176 if (AA->isClaimed()) {
Daniel Dunbar90dd6f42009-04-04 00:52:26 +00003177 DuplicateClaimed = true;
3178 break;
3179 }
3180 }
3181
3182 if (DuplicateClaimed)
3183 continue;
3184 }
3185
Ehsan Akhgarid8518332016-01-25 21:14:52 +00003186 // In clang-cl, don't mention unknown arguments here since they have
3187 // already been warned about.
3188 if (!IsCLMode() || !A->getOption().matches(options::OPT_UNKNOWN))
3189 Diag(clang::diag::warn_drv_unused_argument)
3190 << A->getAsString(C.getArgs());
Daniel Dunbar90dd6f42009-04-04 00:52:26 +00003191 }
Daniel Dunbar3ce436d2009-03-16 06:42:30 +00003192 }
Daniel Dunbar95e6b192009-03-13 22:12:33 +00003193}
Daniel Dunbarc4343942010-02-03 03:07:56 +00003194
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00003195namespace {
3196/// Utility class to control the collapse of dependent actions and select the
3197/// tools accordingly.
3198class ToolSelector final {
3199 /// The tool chain this selector refers to.
3200 const ToolChain &TC;
Daniel Dunbarf9ff3502010-05-14 02:03:00 +00003201
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00003202 /// The compilation this selector refers to.
3203 const Compilation &C;
Samuel Antaod06239d2016-07-15 23:13:27 +00003204
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00003205 /// The base action this selector refers to.
3206 const JobAction *BaseAction;
Samuel Antaod06239d2016-07-15 23:13:27 +00003207
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00003208 /// Set to true if the current toolchain refers to host actions.
3209 bool IsHostSelector;
Samuel Antaod06239d2016-07-15 23:13:27 +00003210
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00003211 /// Set to true if save-temps and embed-bitcode functionalities are active.
3212 bool SaveTemps;
3213 bool EmbedBitcode;
3214
3215 /// Get previous dependent action or null if that does not exist. If
3216 /// \a CanBeCollapsed is false, that action must be legal to collapse or
3217 /// null will be returned.
3218 const JobAction *getPrevDependentAction(const ActionList &Inputs,
3219 ActionList &SavedOffloadAction,
3220 bool CanBeCollapsed = true) {
3221 // An option can be collapsed only if it has a single input.
3222 if (Inputs.size() != 1)
Craig Topper92fc2df2014-05-17 16:56:41 +00003223 return nullptr;
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00003224
3225 Action *CurAction = *Inputs.begin();
3226 if (CanBeCollapsed &&
3227 !CurAction->isCollapsingWithNextDependentActionLegal())
3228 return nullptr;
3229
3230 // If the input action is an offload action. Look through it and save any
3231 // offload action that can be dropped in the event of a collapse.
3232 if (auto *OA = dyn_cast<OffloadAction>(CurAction)) {
3233 // If the dependent action is a device action, we will attempt to collapse
3234 // only with other device actions. Otherwise, we would do the same but
3235 // with host actions only.
3236 if (!IsHostSelector) {
3237 if (OA->hasSingleDeviceDependence(/*DoNotConsiderHostActions=*/true)) {
3238 CurAction =
3239 OA->getSingleDeviceDependence(/*DoNotConsiderHostActions=*/true);
3240 if (CanBeCollapsed &&
3241 !CurAction->isCollapsingWithNextDependentActionLegal())
3242 return nullptr;
3243 SavedOffloadAction.push_back(OA);
3244 return dyn_cast<JobAction>(CurAction);
3245 }
3246 } else if (OA->hasHostDependence()) {
3247 CurAction = OA->getHostDependence();
3248 if (CanBeCollapsed &&
3249 !CurAction->isCollapsingWithNextDependentActionLegal())
3250 return nullptr;
3251 SavedOffloadAction.push_back(OA);
3252 return dyn_cast<JobAction>(CurAction);
3253 }
3254 return nullptr;
3255 }
3256
3257 return dyn_cast<JobAction>(CurAction);
3258 }
3259
3260 /// Return true if an assemble action can be collapsed.
3261 bool canCollapseAssembleAction() const {
3262 return TC.useIntegratedAs() && !SaveTemps &&
3263 !C.getArgs().hasArg(options::OPT_via_file_asm) &&
3264 !C.getArgs().hasArg(options::OPT__SLASH_FA) &&
3265 !C.getArgs().hasArg(options::OPT__SLASH_Fa);
3266 }
3267
3268 /// Return true if a preprocessor action can be collapsed.
3269 bool canCollapsePreprocessorAction() const {
3270 return !C.getArgs().hasArg(options::OPT_no_integrated_cpp) &&
3271 !C.getArgs().hasArg(options::OPT_traditional_cpp) && !SaveTemps &&
3272 !C.getArgs().hasArg(options::OPT_rewrite_objc);
3273 }
3274
3275 /// Struct that relates an action with the offload actions that would be
3276 /// collapsed with it.
3277 struct JobActionInfo final {
3278 /// The action this info refers to.
3279 const JobAction *JA = nullptr;
3280 /// The offload actions we need to take care off if this action is
3281 /// collapsed.
3282 ActionList SavedOffloadAction;
3283 };
3284
3285 /// Append collapsed offload actions from the give nnumber of elements in the
3286 /// action info array.
3287 static void AppendCollapsedOffloadAction(ActionList &CollapsedOffloadAction,
3288 ArrayRef<JobActionInfo> &ActionInfo,
3289 unsigned ElementNum) {
3290 assert(ElementNum <= ActionInfo.size() && "Invalid number of elements.");
3291 for (unsigned I = 0; I < ElementNum; ++I)
3292 CollapsedOffloadAction.append(ActionInfo[I].SavedOffloadAction.begin(),
3293 ActionInfo[I].SavedOffloadAction.end());
3294 }
3295
3296 /// Functions that attempt to perform the combining. They detect if that is
3297 /// legal, and if so they update the inputs \a Inputs and the offload action
3298 /// that were collapsed in \a CollapsedOffloadAction. A tool that deals with
3299 /// the combined action is returned. If the combining is not legal or if the
3300 /// tool does not exist, null is returned.
3301 /// Currently three kinds of collapsing are supported:
3302 /// - Assemble + Backend + Compile;
3303 /// - Assemble + Backend ;
3304 /// - Backend + Compile.
3305 const Tool *
3306 combineAssembleBackendCompile(ArrayRef<JobActionInfo> ActionInfo,
3307 const ActionList *&Inputs,
3308 ActionList &CollapsedOffloadAction) {
3309 if (ActionInfo.size() < 3 || !canCollapseAssembleAction())
3310 return nullptr;
3311 auto *AJ = dyn_cast<AssembleJobAction>(ActionInfo[0].JA);
3312 auto *BJ = dyn_cast<BackendJobAction>(ActionInfo[1].JA);
3313 auto *CJ = dyn_cast<CompileJobAction>(ActionInfo[2].JA);
3314 if (!AJ || !BJ || !CJ)
3315 return nullptr;
3316
3317 // Get compiler tool.
3318 const Tool *T = TC.SelectTool(*CJ);
3319 if (!T)
3320 return nullptr;
3321
Steven Wu574b0f22016-03-01 01:07:58 +00003322 // When using -fembed-bitcode, it is required to have the same tool (clang)
3323 // for both CompilerJA and BackendJA. Otherwise, combine two stages.
3324 if (EmbedBitcode) {
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00003325 const Tool *BT = TC.SelectTool(*BJ);
3326 if (BT == T)
3327 return nullptr;
Steven Wu574b0f22016-03-01 01:07:58 +00003328 }
Bob Wilson23a55f12014-12-21 07:00:00 +00003329
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00003330 if (!T->hasIntegratedAssembler())
Bob Wilson23a55f12014-12-21 07:00:00 +00003331 return nullptr;
Samuel Antaod06239d2016-07-15 23:13:27 +00003332
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00003333 Inputs = &CJ->getInputs();
3334 AppendCollapsedOffloadAction(CollapsedOffloadAction, ActionInfo,
3335 /*NumElements=*/3);
3336 return T;
3337 }
3338 const Tool *combineAssembleBackend(ArrayRef<JobActionInfo> ActionInfo,
3339 const ActionList *&Inputs,
3340 ActionList &CollapsedOffloadAction) {
3341 if (ActionInfo.size() < 2 || !canCollapseAssembleAction())
3342 return nullptr;
3343 auto *AJ = dyn_cast<AssembleJobAction>(ActionInfo[0].JA);
3344 auto *BJ = dyn_cast<BackendJobAction>(ActionInfo[1].JA);
3345 if (!AJ || !BJ)
3346 return nullptr;
3347
3348 // Retrieve the compile job, backend action must always be preceded by one.
3349 ActionList CompileJobOffloadActions;
3350 auto *CJ = getPrevDependentAction(BJ->getInputs(), CompileJobOffloadActions,
3351 /*CanBeCollapsed=*/false);
3352 if (!AJ || !BJ || !CJ)
3353 return nullptr;
3354
3355 assert(isa<CompileJobAction>(CJ) &&
3356 "Expecting compile job preceding backend job.");
3357
3358 // Get compiler tool.
3359 const Tool *T = TC.SelectTool(*CJ);
3360 if (!T)
3361 return nullptr;
3362
3363 if (!T->hasIntegratedAssembler())
3364 return nullptr;
3365
3366 Inputs = &BJ->getInputs();
3367 AppendCollapsedOffloadAction(CollapsedOffloadAction, ActionInfo,
3368 /*NumElements=*/2);
3369 return T;
3370 }
3371 const Tool *combineBackendCompile(ArrayRef<JobActionInfo> ActionInfo,
3372 const ActionList *&Inputs,
3373 ActionList &CollapsedOffloadAction) {
3374 if (ActionInfo.size() < 2 || !canCollapsePreprocessorAction())
3375 return nullptr;
3376 auto *BJ = dyn_cast<BackendJobAction>(ActionInfo[0].JA);
3377 auto *CJ = dyn_cast<CompileJobAction>(ActionInfo[1].JA);
3378 if (!BJ || !CJ)
3379 return nullptr;
3380
3381 // Get compiler tool.
3382 const Tool *T = TC.SelectTool(*CJ);
3383 if (!T)
3384 return nullptr;
3385
3386 if (T->canEmitIR() && (SaveTemps || EmbedBitcode))
3387 return nullptr;
3388
3389 Inputs = &CJ->getInputs();
3390 AppendCollapsedOffloadAction(CollapsedOffloadAction, ActionInfo,
3391 /*NumElements=*/2);
3392 return T;
3393 }
3394
3395 /// Updates the inputs if the obtained tool supports combining with
3396 /// preprocessor action, and the current input is indeed a preprocessor
3397 /// action. If combining results in the collapse of offloading actions, those
3398 /// are appended to \a CollapsedOffloadAction.
3399 void combineWithPreprocessor(const Tool *T, const ActionList *&Inputs,
3400 ActionList &CollapsedOffloadAction) {
3401 if (!T || !canCollapsePreprocessorAction() || !T->hasIntegratedCPP())
3402 return;
3403
3404 // Attempt to get a preprocessor action dependence.
3405 ActionList PreprocessJobOffloadActions;
3406 auto *PJ = getPrevDependentAction(*Inputs, PreprocessJobOffloadActions);
3407 if (!PJ || !isa<PreprocessJobAction>(PJ))
3408 return;
3409
3410 // This is legal to combine. Append any offload action we found and set the
3411 // current inputs to preprocessor inputs.
3412 CollapsedOffloadAction.append(PreprocessJobOffloadActions.begin(),
3413 PreprocessJobOffloadActions.end());
3414 Inputs = &PJ->getInputs();
3415 }
3416
3417public:
3418 ToolSelector(const JobAction *BaseAction, const ToolChain &TC,
3419 const Compilation &C, bool SaveTemps, bool EmbedBitcode)
3420 : TC(TC), C(C), BaseAction(BaseAction), SaveTemps(SaveTemps),
3421 EmbedBitcode(EmbedBitcode) {
3422 assert(BaseAction && "Invalid base action.");
3423 IsHostSelector = BaseAction->getOffloadingDeviceKind() == Action::OFK_None;
3424 }
3425
3426 /// Check if a chain of actions can be combined and return the tool that can
3427 /// handle the combination of actions. The pointer to the current inputs \a
3428 /// Inputs and the list of offload actions \a CollapsedOffloadActions
3429 /// connected to collapsed actions are updated accordingly. The latter enables
3430 /// the caller of the selector to process them afterwards instead of just
3431 /// dropping them. If no suitable tool is found, null will be returned.
3432 const Tool *getTool(const ActionList *&Inputs,
3433 ActionList &CollapsedOffloadAction) {
3434 //
3435 // Get the largest chain of actions that we could combine.
3436 //
3437
3438 SmallVector<JobActionInfo, 5> ActionChain(1);
3439 ActionChain.back().JA = BaseAction;
3440 while (ActionChain.back().JA) {
3441 const Action *CurAction = ActionChain.back().JA;
3442
3443 // Grow the chain by one element.
3444 ActionChain.resize(ActionChain.size() + 1);
3445 JobActionInfo &AI = ActionChain.back();
3446
3447 // Attempt to fill it with the
3448 AI.JA =
3449 getPrevDependentAction(CurAction->getInputs(), AI.SavedOffloadAction);
Daniel Dunbarc4343942010-02-03 03:07:56 +00003450 }
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00003451
3452 // Pop the last action info as it could not be filled.
3453 ActionChain.pop_back();
3454
3455 //
3456 // Attempt to combine actions. If all combining attempts failed, just return
3457 // the tool of the provided action. At the end we attempt to combine the
3458 // action with any preprocessor action it may depend on.
3459 //
3460
3461 const Tool *T = combineAssembleBackendCompile(ActionChain, Inputs,
3462 CollapsedOffloadAction);
3463 if (!T)
3464 T = combineAssembleBackend(ActionChain, Inputs, CollapsedOffloadAction);
3465 if (!T)
3466 T = combineBackendCompile(ActionChain, Inputs, CollapsedOffloadAction);
3467 if (!T) {
3468 Inputs = &BaseAction->getInputs();
3469 T = TC.SelectTool(*BaseAction);
3470 }
3471
3472 combineWithPreprocessor(T, Inputs, CollapsedOffloadAction);
3473 return T;
Daniel Dunbarc4343942010-02-03 03:07:56 +00003474 }
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00003475};
Daniel Dunbarc4343942010-02-03 03:07:56 +00003476}
3477
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003478/// Return a string that uniquely identifies the result of a job. The bound arch
3479/// is not necessarily represented in the toolchain's triple -- for example,
3480/// armv7 and armv7s both map to the same triple -- so we need both in our map.
3481/// Also, we need to add the offloading device kind, as the same tool chain can
3482/// be used for host and device for some programming models, e.g. OpenMP.
3483static std::string GetTriplePlusArchString(const ToolChain *TC,
3484 StringRef BoundArch,
3485 Action::OffloadKind OffloadKind) {
Justin Lebar55c83322016-01-16 03:30:08 +00003486 std::string TriplePlusArch = TC->getTriple().normalize();
Mehdi Aminic50b1a22016-10-07 21:27:26 +00003487 if (!BoundArch.empty()) {
Justin Lebar55c83322016-01-16 03:30:08 +00003488 TriplePlusArch += "-";
3489 TriplePlusArch += BoundArch;
3490 }
Samuel Antao59efaed2016-10-27 17:31:22 +00003491 TriplePlusArch += "-";
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003492 TriplePlusArch += Action::GetOffloadKindName(OffloadKind);
3493 return TriplePlusArch;
3494}
3495
3496InputInfo Driver::BuildJobsForAction(
3497 Compilation &C, const Action *A, const ToolChain *TC, StringRef BoundArch,
3498 bool AtTopLevel, bool MultipleArchs, const char *LinkingOutput,
3499 std::map<std::pair<const Action *, std::string>, InputInfo> &CachedResults,
3500 Action::OffloadKind TargetDeviceOffloadKind) const {
3501 std::pair<const Action *, std::string> ActionTC = {
3502 A, GetTriplePlusArchString(TC, BoundArch, TargetDeviceOffloadKind)};
Justin Lebarb44f6fe2016-01-14 21:41:21 +00003503 auto CachedResult = CachedResults.find(ActionTC);
3504 if (CachedResult != CachedResults.end()) {
3505 return CachedResult->second;
3506 }
Samuel Antaod06239d2016-07-15 23:13:27 +00003507 InputInfo Result = BuildJobsForActionNoCache(
3508 C, A, TC, BoundArch, AtTopLevel, MultipleArchs, LinkingOutput,
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003509 CachedResults, TargetDeviceOffloadKind);
Justin Lebarb44f6fe2016-01-14 21:41:21 +00003510 CachedResults[ActionTC] = Result;
3511 return Result;
3512}
3513
3514InputInfo Driver::BuildJobsForActionNoCache(
Mehdi Aminic50b1a22016-10-07 21:27:26 +00003515 Compilation &C, const Action *A, const ToolChain *TC, StringRef BoundArch,
Justin Lebarb44f6fe2016-01-14 21:41:21 +00003516 bool AtTopLevel, bool MultipleArchs, const char *LinkingOutput,
Samuel Antaod06239d2016-07-15 23:13:27 +00003517 std::map<std::pair<const Action *, std::string>, InputInfo> &CachedResults,
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003518 Action::OffloadKind TargetDeviceOffloadKind) const {
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00003519 llvm::PrettyStackTraceString CrashInfo("Building compilation jobs");
Daniel Dunbarc4acf9d2009-03-18 23:18:19 +00003520
Samuel Antaod06239d2016-07-15 23:13:27 +00003521 InputInfoList OffloadDependencesInputInfo;
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003522 bool BuildingForOffloadDevice = TargetDeviceOffloadKind != Action::OFK_None;
Samuel Antaod06239d2016-07-15 23:13:27 +00003523 if (const OffloadAction *OA = dyn_cast<OffloadAction>(A)) {
Alex Lorenz4003a982017-08-08 11:22:21 +00003524 // The 'Darwin' toolchain is initialized only when its arguments are
3525 // computed. Get the default arguments for OFK_None to ensure that
3526 // initialization is performed before processing the offload action.
3527 // FIXME: Remove when darwin's toolchain is initialized during construction.
3528 C.getArgsForToolChain(TC, BoundArch, Action::OFK_None);
3529
Samuel Antaod06239d2016-07-15 23:13:27 +00003530 // The offload action is expected to be used in four different situations.
3531 //
3532 // a) Set a toolchain/architecture/kind for a host action:
3533 // Host Action 1 -> OffloadAction -> Host Action 2
3534 //
3535 // b) Set a toolchain/architecture/kind for a device action;
3536 // Device Action 1 -> OffloadAction -> Device Action 2
3537 //
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00003538 // c) Specify a device dependence to a host action;
Samuel Antaod06239d2016-07-15 23:13:27 +00003539 // Device Action 1 _
3540 // \
3541 // Host Action 1 ---> OffloadAction -> Host Action 2
3542 //
3543 // d) Specify a host dependence to a device action.
3544 // Host Action 1 _
3545 // \
3546 // Device Action 1 ---> OffloadAction -> Device Action 2
3547 //
3548 // For a) and b), we just return the job generated for the dependence. For
3549 // c) and d) we override the current action with the host/device dependence
3550 // if the current toolchain is host/device and set the offload dependences
3551 // info with the jobs obtained from the device/host dependence(s).
3552
3553 // If there is a single device option, just generate the job for it.
3554 if (OA->hasSingleDeviceDependence()) {
3555 InputInfo DevA;
3556 OA->doOnEachDeviceDependence([&](Action *DepA, const ToolChain *DepTC,
3557 const char *DepBoundArch) {
3558 DevA =
3559 BuildJobsForAction(C, DepA, DepTC, DepBoundArch, AtTopLevel,
3560 /*MultipleArchs*/ !!DepBoundArch, LinkingOutput,
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003561 CachedResults, DepA->getOffloadingDeviceKind());
Samuel Antaod06239d2016-07-15 23:13:27 +00003562 });
3563 return DevA;
Artem Belevich0ff05cd2015-07-13 23:27:56 +00003564 }
Samuel Antaod06239d2016-07-15 23:13:27 +00003565
3566 // If 'Action 2' is host, we generate jobs for the device dependences and
3567 // override the current action with the host dependence. Otherwise, we
3568 // generate the host dependences and override the action with the device
3569 // dependence. The dependences can't therefore be a top-level action.
3570 OA->doOnEachDependence(
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003571 /*IsHostDependence=*/BuildingForOffloadDevice,
Samuel Antaod06239d2016-07-15 23:13:27 +00003572 [&](Action *DepA, const ToolChain *DepTC, const char *DepBoundArch) {
3573 OffloadDependencesInputInfo.push_back(BuildJobsForAction(
3574 C, DepA, DepTC, DepBoundArch, /*AtTopLevel=*/false,
3575 /*MultipleArchs*/ !!DepBoundArch, LinkingOutput, CachedResults,
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003576 DepA->getOffloadingDeviceKind()));
Samuel Antaod06239d2016-07-15 23:13:27 +00003577 });
3578
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003579 A = BuildingForOffloadDevice
Samuel Antaod06239d2016-07-15 23:13:27 +00003580 ? OA->getSingleDeviceDependence(/*DoNotConsiderHostActions=*/true)
3581 : OA->getHostDependence();
Artem Belevich0ff05cd2015-07-13 23:27:56 +00003582 }
3583
Daniel Dunbare75d8342009-03-16 06:56:51 +00003584 if (const InputAction *IA = dyn_cast<InputAction>(A)) {
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00003585 // FIXME: It would be nice to not claim this here; maybe the old scheme of
3586 // just using Args was better?
Daniel Dunbar5cdf3e02009-03-19 07:29:38 +00003587 const Arg &Input = IA->getInputArg();
3588 Input.claim();
Daniel Dunbar35cbfeb2010-06-09 22:31:08 +00003589 if (Input.getOption().matches(options::OPT_INPUT)) {
Richard Smithbd55daf2012-11-01 04:30:05 +00003590 const char *Name = Input.getValue();
Justin Lebard98cea82016-01-11 23:15:21 +00003591 return InputInfo(A, Name, /* BaseInput = */ Name);
Douglas Katzman678d0cb2015-06-16 18:01:24 +00003592 }
Justin Lebard98cea82016-01-11 23:15:21 +00003593 return InputInfo(A, &Input, /* BaseInput = */ "");
Daniel Dunbare75d8342009-03-16 06:56:51 +00003594 }
3595
3596 if (const BindArchAction *BAA = dyn_cast<BindArchAction>(A)) {
Chad Rosiera78a6eb2012-04-27 16:50:38 +00003597 const ToolChain *TC;
Mehdi Aminic50b1a22016-10-07 21:27:26 +00003598 StringRef ArchName = BAA->getArchName();
Daniel Dunbar1ef3f2a2009-09-08 23:37:19 +00003599
Mehdi Aminic50b1a22016-10-07 21:27:26 +00003600 if (!ArchName.empty())
Andrey Turetskiy6a8b91d2016-04-21 10:16:48 +00003601 TC = &getToolChain(C.getArgs(),
3602 computeTargetTriple(*this, DefaultTargetTriple,
3603 C.getArgs(), ArchName));
Chad Rosiera78a6eb2012-04-27 16:50:38 +00003604 else
3605 TC = &C.getDefaultToolChain();
Daniel Dunbar1ef3f2a2009-09-08 23:37:19 +00003606
Nico Weber5a459f82016-02-23 19:30:43 +00003607 return BuildJobsForAction(C, *BAA->input_begin(), TC, ArchName, AtTopLevel,
Samuel Antaod06239d2016-07-15 23:13:27 +00003608 MultipleArchs, LinkingOutput, CachedResults,
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003609 TargetDeviceOffloadKind);
Daniel Dunbare75d8342009-03-16 06:56:51 +00003610 }
3611
Artem Belevich0ff05cd2015-07-13 23:27:56 +00003612
Daniel Dunbare75d8342009-03-16 06:56:51 +00003613 const ActionList *Inputs = &A->getInputs();
Daniel Dunbarc4343942010-02-03 03:07:56 +00003614
3615 const JobAction *JA = cast<JobAction>(A);
Samuel Antaod06239d2016-07-15 23:13:27 +00003616 ActionList CollapsedOffloadActions;
3617
Mehdi Amini6683e222017-01-24 18:12:25 +00003618 ToolSelector TS(JA, *TC, C, isSaveTempsEnabled(),
3619 embedBitcodeInObject() && !isUsingLTO());
Samuel Antao9c9d9cd2016-10-27 16:29:20 +00003620 const Tool *T = TS.getTool(Inputs, CollapsedOffloadActions);
3621
Rafael Espindola79764462013-03-24 15:06:53 +00003622 if (!T)
Justin Lebar9eaa4892016-01-11 23:09:32 +00003623 return InputInfo();
Daniel Dunbare75d8342009-03-16 06:56:51 +00003624
Samuel Antaod06239d2016-07-15 23:13:27 +00003625 // If we've collapsed action list that contained OffloadAction we
3626 // need to build jobs for host/device-side inputs it may have held.
3627 for (const auto *OA : CollapsedOffloadActions)
3628 cast<OffloadAction>(OA)->doOnEachDependence(
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003629 /*IsHostDependence=*/BuildingForOffloadDevice,
Samuel Antaod06239d2016-07-15 23:13:27 +00003630 [&](Action *DepA, const ToolChain *DepTC, const char *DepBoundArch) {
3631 OffloadDependencesInputInfo.push_back(BuildJobsForAction(
Artem Belevichbee2f412016-08-22 18:50:34 +00003632 C, DepA, DepTC, DepBoundArch, /* AtTopLevel */ false,
Samuel Antaod06239d2016-07-15 23:13:27 +00003633 /*MultipleArchs=*/!!DepBoundArch, LinkingOutput, CachedResults,
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003634 DepA->getOffloadingDeviceKind()));
Samuel Antaod06239d2016-07-15 23:13:27 +00003635 });
Artem Belevichf8144ab2015-08-27 18:10:41 +00003636
Daniel Dunbare75d8342009-03-16 06:56:51 +00003637 // Only use pipes when there is exactly one input.
Daniel Dunbar1a093d22009-03-18 06:00:36 +00003638 InputInfoList InputInfos;
Saleem Abdulrasoolda3f4e52014-12-29 21:02:47 +00003639 for (const Action *Input : *Inputs) {
Eric Christopher14668dd2013-02-18 00:38:25 +00003640 // Treat dsymutil and verify sub-jobs as being at the top-level too, they
3641 // shouldn't get temporary output names.
Daniel Dunbar6beaf512010-06-04 18:28:41 +00003642 // FIXME: Clean this up.
Justin Lebar9eaa4892016-01-11 23:09:32 +00003643 bool SubJobAtTopLevel =
3644 AtTopLevel && (isa<DsymutilJobAction>(A) || isa<VerifyJobAction>(A));
Samuel Antaod06239d2016-07-15 23:13:27 +00003645 InputInfos.push_back(BuildJobsForAction(
3646 C, Input, TC, BoundArch, SubJobAtTopLevel, MultipleArchs, LinkingOutput,
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003647 CachedResults, A->getOffloadingDeviceKind()));
Daniel Dunbare75d8342009-03-16 06:56:51 +00003648 }
3649
Daniel Dunbare75d8342009-03-16 06:56:51 +00003650 // Always use the first input as the base input.
3651 const char *BaseInput = InputInfos[0].getBaseInput();
Daniel Dunbar7a178a42009-03-17 17:53:55 +00003652
Daniel Dunbar6beaf512010-06-04 18:28:41 +00003653 // ... except dsymutil actions, which use their actual input as the base
3654 // input.
3655 if (JA->getType() == types::TY_dSYM)
3656 BaseInput = InputInfos[0].getFilename();
3657
Samuel Antaod06239d2016-07-15 23:13:27 +00003658 // Append outputs of offload device jobs to the input list
3659 if (!OffloadDependencesInputInfo.empty())
3660 InputInfos.append(OffloadDependencesInputInfo.begin(),
3661 OffloadDependencesInputInfo.end());
Artem Belevich0ff05cd2015-07-13 23:27:56 +00003662
Vedant Kumar18286cf2016-07-27 23:02:20 +00003663 // Set the effective triple of the toolchain for the duration of this job.
3664 llvm::Triple EffectiveTriple;
3665 const ToolChain &ToolTC = T->getToolChain();
Samuel Antao31fef982016-10-27 17:39:44 +00003666 const ArgList &Args =
3667 C.getArgsForToolChain(TC, BoundArch, A->getOffloadingDeviceKind());
Vedant Kumar18286cf2016-07-27 23:02:20 +00003668 if (InputInfos.size() != 1) {
3669 EffectiveTriple = llvm::Triple(ToolTC.ComputeEffectiveClangTriple(Args));
3670 } else {
3671 // Pass along the input type if it can be unambiguously determined.
3672 EffectiveTriple = llvm::Triple(
3673 ToolTC.ComputeEffectiveClangTriple(Args, InputInfos[0].getType()));
3674 }
3675 RegisterEffectiveTriple TripleRAII(ToolTC, EffectiveTriple);
3676
Daniel Dunbard00272f2010-08-02 02:38:15 +00003677 // Determine the place to write output to, if any.
Justin Lebar9eaa4892016-01-11 23:09:32 +00003678 InputInfo Result;
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003679 InputInfoList UnbundlingResults;
3680 if (auto *UA = dyn_cast<OffloadUnbundlingJobAction>(JA)) {
3681 // If we have an unbundling job, we need to create results for all the
3682 // outputs. We also update the results cache so that other actions using
3683 // this unbundling action can get the right results.
3684 for (auto &UI : UA->getDependentActionsInfo()) {
3685 assert(UI.DependentOffloadKind != Action::OFK_None &&
3686 "Unbundling with no offloading??");
3687
3688 // Unbundling actions are never at the top level. When we generate the
3689 // offloading prefix, we also do that for the host file because the
3690 // unbundling action does not change the type of the output which can
3691 // cause a overwrite.
3692 std::string OffloadingPrefix = Action::GetOffloadingFileNamePrefix(
3693 UI.DependentOffloadKind,
3694 UI.DependentToolChain->getTriple().normalize(),
3695 /*CreatePrefixForHost=*/true);
3696 auto CurI = InputInfo(
3697 UA, GetNamedOutputPath(C, *UA, BaseInput, UI.DependentBoundArch,
3698 /*AtTopLevel=*/false, MultipleArchs,
3699 OffloadingPrefix),
3700 BaseInput);
3701 // Save the unbundling result.
3702 UnbundlingResults.push_back(CurI);
3703
3704 // Get the unique string identifier for this dependence and cache the
3705 // result.
3706 CachedResults[{A, GetTriplePlusArchString(
Gheorghe-Teodor Bercea52898432017-08-09 01:02:19 +00003707 UI.DependentToolChain, BoundArch,
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003708 UI.DependentOffloadKind)}] = CurI;
3709 }
3710
3711 // Now that we have all the results generated, select the one that should be
3712 // returned for the current depending action.
3713 std::pair<const Action *, std::string> ActionTC = {
3714 A, GetTriplePlusArchString(TC, BoundArch, TargetDeviceOffloadKind)};
3715 assert(CachedResults.find(ActionTC) != CachedResults.end() &&
3716 "Result does not exist??");
3717 Result = CachedResults[ActionTC];
3718 } else if (JA->getType() == types::TY_Nothing)
Justin Lebard98cea82016-01-11 23:15:21 +00003719 Result = InputInfo(A, BaseInput);
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003720 else {
3721 // We only have to generate a prefix for the host if this is not a top-level
3722 // action.
3723 std::string OffloadingPrefix = Action::GetOffloadingFileNamePrefix(
3724 A->getOffloadingDeviceKind(), TC->getTriple().normalize(),
3725 /*CreatePrefixForHost=*/!!A->getOffloadingHostActiveKinds() &&
3726 !AtTopLevel);
Justin Lebard98cea82016-01-11 23:15:21 +00003727 Result = InputInfo(A, GetNamedOutputPath(C, *JA, BaseInput, BoundArch,
Samuel Antaod06239d2016-07-15 23:13:27 +00003728 AtTopLevel, MultipleArchs,
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003729 OffloadingPrefix),
Justin Lebard98cea82016-01-11 23:15:21 +00003730 BaseInput);
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003731 }
Daniel Dunbar7a178a42009-03-17 17:53:55 +00003732
Chad Rosierbe10f982011-08-02 17:58:04 +00003733 if (CCCPrintBindings && !CCGenDiagnostics) {
Rafael Espindola79764462013-03-24 15:06:53 +00003734 llvm::errs() << "# \"" << T->getToolChain().getTripleString() << '"'
3735 << " - \"" << T->getName() << "\", inputs: [";
Daniel Dunbarb39cc522009-03-17 22:47:06 +00003736 for (unsigned i = 0, e = InputInfos.size(); i != e; ++i) {
3737 llvm::errs() << InputInfos[i].getAsString();
3738 if (i + 1 != e)
3739 llvm::errs() << ", ";
3740 }
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003741 if (UnbundlingResults.empty())
3742 llvm::errs() << "], output: " << Result.getAsString() << "\n";
3743 else {
3744 llvm::errs() << "], outputs: [";
3745 for (unsigned i = 0, e = UnbundlingResults.size(); i != e; ++i) {
3746 llvm::errs() << UnbundlingResults[i].getAsString();
3747 if (i + 1 != e)
3748 llvm::errs() << ", ";
3749 }
3750 llvm::errs() << "] \n";
3751 }
Daniel Dunbarb39cc522009-03-17 22:47:06 +00003752 } else {
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003753 if (UnbundlingResults.empty())
3754 T->ConstructJob(
3755 C, *JA, Result, InputInfos,
3756 C.getArgsForToolChain(TC, BoundArch, JA->getOffloadingDeviceKind()),
3757 LinkingOutput);
3758 else
Samuel Antao7108bf32016-11-03 15:41:50 +00003759 T->ConstructJobMultipleOutputs(
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003760 C, *JA, UnbundlingResults, InputInfos,
3761 C.getArgsForToolChain(TC, BoundArch, JA->getOffloadingDeviceKind()),
3762 LinkingOutput);
Daniel Dunbarb39cc522009-03-17 22:47:06 +00003763 }
Justin Lebar9eaa4892016-01-11 23:09:32 +00003764 return Result;
Daniel Dunbare75d8342009-03-16 06:56:51 +00003765}
3766
Hans Wennborga7707222015-01-09 17:38:53 +00003767const char *Driver::getDefaultImageName() const {
3768 llvm::Triple Target(llvm::Triple::normalize(DefaultTargetTriple));
3769 return Target.isOSWindows() ? "a.exe" : "a.out";
3770}
3771
Hans Wennborg2c21f742013-10-17 16:16:23 +00003772/// \brief Create output filename based on ArgValue, which could either be a
3773/// full filename, filename without extension, or a directory. If ArgValue
3774/// does not provide a filename, then use BaseName, and use the extension
3775/// suitable for FileType.
Hans Wennborg207fcf02013-08-12 21:56:42 +00003776static const char *MakeCLOutputFilename(const ArgList &Args, StringRef ArgValue,
Douglas Katzmana67e50c2015-06-26 15:47:46 +00003777 StringRef BaseName,
3778 types::ID FileType) {
Hans Wennborg207fcf02013-08-12 21:56:42 +00003779 SmallString<128> Filename = ArgValue;
Justin Bogner5aaf2e72014-06-26 20:59:36 +00003780
Hans Wennborgf1a74252013-09-10 20:18:04 +00003781 if (ArgValue.empty()) {
3782 // If the argument is empty, output to BaseName in the current dir.
3783 Filename = BaseName;
3784 } else if (llvm::sys::path::is_separator(Filename.back())) {
Hans Wennborg207fcf02013-08-12 21:56:42 +00003785 // If the argument is a directory, output to BaseName in that dir.
3786 llvm::sys::path::append(Filename, BaseName);
3787 }
3788
3789 if (!llvm::sys::path::has_extension(ArgValue)) {
3790 // If the argument didn't provide an extension, then set it.
3791 const char *Extension = types::getTypeTempSuffix(FileType, true);
Hans Wennborgf1a74252013-09-10 20:18:04 +00003792
3793 if (FileType == types::TY_Image &&
3794 Args.hasArg(options::OPT__SLASH_LD, options::OPT__SLASH_LDd)) {
3795 // The output file is a dll.
3796 Extension = "dll";
3797 }
3798
Hans Wennborg207fcf02013-08-12 21:56:42 +00003799 llvm::sys::path::replace_extension(Filename, Extension);
3800 }
3801
3802 return Args.MakeArgString(Filename.c_str());
3803}
3804
Douglas Katzmana67e50c2015-06-26 15:47:46 +00003805const char *Driver::GetNamedOutputPath(Compilation &C, const JobAction &JA,
Daniel Dunbar7a178a42009-03-17 17:53:55 +00003806 const char *BaseInput,
Mehdi Aminic50b1a22016-10-07 21:27:26 +00003807 StringRef BoundArch, bool AtTopLevel,
Samuel Antaod06239d2016-07-15 23:13:27 +00003808 bool MultipleArchs,
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003809 StringRef OffloadingPrefix) const {
Daniel Dunbar2608c542009-03-18 01:38:48 +00003810 llvm::PrettyStackTraceString CrashInfo("Computing output path");
Daniel Dunbar7a178a42009-03-17 17:53:55 +00003811 // Output to a user requested destination?
Douglas Katzmana67e50c2015-06-26 15:47:46 +00003812 if (AtTopLevel && !isa<DsymutilJobAction>(JA) && !isa<VerifyJobAction>(JA)) {
Daniel Dunbar7a178a42009-03-17 17:53:55 +00003813 if (Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o))
Chad Rosier633dcdc2013-01-24 19:14:47 +00003814 return C.addResultFile(FinalOutput->getValue(), &JA);
Daniel Dunbar7a178a42009-03-17 17:53:55 +00003815 }
3816
Hans Wennborge0053472013-12-20 18:40:46 +00003817 // For /P, preprocess to file named after BaseInput.
3818 if (C.getArgs().hasArg(options::OPT__SLASH_P)) {
3819 assert(AtTopLevel && isa<PreprocessJobAction>(JA));
3820 StringRef BaseName = llvm::sys::path::filename(BaseInput);
Hans Wennborg04c764f2014-06-17 00:19:12 +00003821 StringRef NameArg;
Greg Bedwell065f70a2015-06-09 10:24:06 +00003822 if (Arg *A = C.getArgs().getLastArg(options::OPT__SLASH_Fi))
Hans Wennborg04c764f2014-06-17 00:19:12 +00003823 NameArg = A->getValue();
Douglas Katzmana67e50c2015-06-26 15:47:46 +00003824 return C.addResultFile(
3825 MakeCLOutputFilename(C.getArgs(), NameArg, BaseName, types::TY_PP_C),
3826 &JA);
Hans Wennborge0053472013-12-20 18:40:46 +00003827 }
3828
Nick Lewycky6e1ce292010-09-24 00:46:53 +00003829 // Default to writing to stdout?
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +00003830 if (AtTopLevel && !CCGenDiagnostics &&
3831 (isa<PreprocessJobAction>(JA) || JA.getType() == types::TY_ModuleFile))
Nick Lewycky6e1ce292010-09-24 00:46:53 +00003832 return "-";
3833
Hans Wennborg2c21f742013-10-17 16:16:23 +00003834 // Is this the assembly listing for /FA?
3835 if (JA.getType() == types::TY_PP_Asm &&
3836 (C.getArgs().hasArg(options::OPT__SLASH_FA) ||
3837 C.getArgs().hasArg(options::OPT__SLASH_Fa))) {
3838 // Use /Fa and the input filename to determine the asm file name.
3839 StringRef BaseName = llvm::sys::path::filename(BaseInput);
3840 StringRef FaValue = C.getArgs().getLastArgValue(options::OPT__SLASH_Fa);
Douglas Katzmana67e50c2015-06-26 15:47:46 +00003841 return C.addResultFile(
3842 MakeCLOutputFilename(C.getArgs(), FaValue, BaseName, JA.getType()),
3843 &JA);
Hans Wennborg2c21f742013-10-17 16:16:23 +00003844 }
3845
Daniel Dunbar7a178a42009-03-17 17:53:55 +00003846 // Output to a temporary file?
Reid Kleckner68eb60b2015-02-02 22:41:48 +00003847 if ((!AtTopLevel && !isSaveTempsEnabled() &&
Douglas Katzmana67e50c2015-06-26 15:47:46 +00003848 !C.getArgs().hasArg(options::OPT__SLASH_Fo)) ||
Chad Rosierbe10f982011-08-02 17:58:04 +00003849 CCGenDiagnostics) {
Chad Rosier97c37372011-08-26 22:27:02 +00003850 StringRef Name = llvm::sys::path::filename(BaseInput);
3851 std::pair<StringRef, StringRef> Split = Name.split('.');
Douglas Katzmana67e50c2015-06-26 15:47:46 +00003852 std::string TmpName = GetTemporaryPath(
3853 Split.first, types::getTypeTempSuffix(JA.getType(), IsCLMode()));
Malcolm Parsonsf76f6502016-11-02 10:39:27 +00003854 return C.addTempFile(C.getArgs().MakeArgString(TmpName));
Daniel Dunbar7a178a42009-03-17 17:53:55 +00003855 }
3856
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00003857 SmallString<128> BasePath(BaseInput);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003858 StringRef BaseName;
Daniel Dunbar67fea712011-03-25 18:16:51 +00003859
3860 // Dsymutil actions should use the full path.
Eric Christopher551ef452011-08-23 17:56:55 +00003861 if (isa<DsymutilJobAction>(JA) || isa<VerifyJobAction>(JA))
Daniel Dunbar67fea712011-03-25 18:16:51 +00003862 BaseName = BasePath;
3863 else
3864 BaseName = llvm::sys::path::filename(BasePath);
Daniel Dunbar7a178a42009-03-17 17:53:55 +00003865
3866 // Determine what the derived output name should be.
3867 const char *NamedOutput;
Hans Wennborg2b89a262013-08-06 22:11:28 +00003868
Hans Wennborg625fba82016-10-04 21:01:04 +00003869 if ((JA.getType() == types::TY_Object || JA.getType() == types::TY_LTO_BC) &&
Ehsan Akhgari81f36b72014-09-11 18:16:21 +00003870 C.getArgs().hasArg(options::OPT__SLASH_Fo, options::OPT__SLASH_o)) {
3871 // The /Fo or /o flag decides the object filename.
Douglas Katzmana67e50c2015-06-26 15:47:46 +00003872 StringRef Val =
3873 C.getArgs()
3874 .getLastArg(options::OPT__SLASH_Fo, options::OPT__SLASH_o)
3875 ->getValue();
3876 NamedOutput =
3877 MakeCLOutputFilename(C.getArgs(), Val, BaseName, types::TY_Object);
Hans Wennborg207fcf02013-08-12 21:56:42 +00003878 } else if (JA.getType() == types::TY_Image &&
Douglas Katzmana67e50c2015-06-26 15:47:46 +00003879 C.getArgs().hasArg(options::OPT__SLASH_Fe,
3880 options::OPT__SLASH_o)) {
Ehsan Akhgari81f36b72014-09-11 18:16:21 +00003881 // The /Fe or /o flag names the linked file.
Douglas Katzmana67e50c2015-06-26 15:47:46 +00003882 StringRef Val =
3883 C.getArgs()
3884 .getLastArg(options::OPT__SLASH_Fe, options::OPT__SLASH_o)
3885 ->getValue();
3886 NamedOutput =
3887 MakeCLOutputFilename(C.getArgs(), Val, BaseName, types::TY_Image);
Hans Wennborgf1a74252013-09-10 20:18:04 +00003888 } else if (JA.getType() == types::TY_Image) {
Hans Wennborg207fcf02013-08-12 21:56:42 +00003889 if (IsCLMode()) {
3890 // clang-cl uses BaseName for the executable name.
Douglas Katzmana67e50c2015-06-26 15:47:46 +00003891 NamedOutput =
3892 MakeCLOutputFilename(C.getArgs(), "", BaseName, types::TY_Image);
Samuel Antao59efaed2016-10-27 17:31:22 +00003893 } else {
Hans Wennborga7707222015-01-09 17:38:53 +00003894 SmallString<128> Output(getDefaultImageName());
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003895 Output += OffloadingPrefix;
Samuel Antao59efaed2016-10-27 17:31:22 +00003896 if (MultipleArchs && !BoundArch.empty()) {
3897 Output += "-";
3898 Output.append(BoundArch);
3899 }
Chad Rosier35767232013-04-30 22:01:21 +00003900 NamedOutput = C.getArgs().MakeArgString(Output.c_str());
Nico Weber2ca4be92016-03-01 23:16:44 +00003901 }
3902 } else if (JA.getType() == types::TY_PCH && IsCLMode()) {
Malcolm Parsonsf76f6502016-11-02 10:39:27 +00003903 NamedOutput = C.getArgs().MakeArgString(GetClPchPath(C, BaseName));
Daniel Dunbar7a178a42009-03-17 17:53:55 +00003904 } else {
Hans Wennborg0a096a02013-09-05 17:05:56 +00003905 const char *Suffix = types::getTypeTempSuffix(JA.getType(), IsCLMode());
Daniel Dunbar7a178a42009-03-17 17:53:55 +00003906 assert(Suffix && "All types used for output should have a suffix.");
3907
3908 std::string::size_type End = std::string::npos;
3909 if (!types::appendSuffixForType(JA.getType()))
3910 End = BaseName.rfind('.');
Chad Rosier35767232013-04-30 22:01:21 +00003911 SmallString<128> Suffixed(BaseName.substr(0, End));
Samuel Antao3b7e38b2016-10-27 18:14:55 +00003912 Suffixed += OffloadingPrefix;
Mehdi Aminic50b1a22016-10-07 21:27:26 +00003913 if (MultipleArchs && !BoundArch.empty()) {
Chad Rosier35767232013-04-30 22:01:21 +00003914 Suffixed += "-";
3915 Suffixed.append(BoundArch);
3916 }
Bob Wilson23a55f12014-12-21 07:00:00 +00003917 // When using both -save-temps and -emit-llvm, use a ".tmp.bc" suffix for
3918 // the unoptimized bitcode so that it does not get overwritten by the ".bc"
3919 // optimized bitcode output.
3920 if (!AtTopLevel && C.getArgs().hasArg(options::OPT_emit_llvm) &&
3921 JA.getType() == types::TY_LLVM_BC)
3922 Suffixed += ".tmp";
Daniel Dunbar7a178a42009-03-17 17:53:55 +00003923 Suffixed += '.';
3924 Suffixed += Suffix;
3925 NamedOutput = C.getArgs().MakeArgString(Suffixed.c_str());
3926 }
3927
Reid Kleckner68eb60b2015-02-02 22:41:48 +00003928 // Prepend object file path if -save-temps=obj
3929 if (!AtTopLevel && isSaveTempsObj() && C.getArgs().hasArg(options::OPT_o) &&
3930 JA.getType() != types::TY_PCH) {
3931 Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o);
3932 SmallString<128> TempPath(FinalOutput->getValue());
3933 llvm::sys::path::remove_filename(TempPath);
3934 StringRef OutputFileName = llvm::sys::path::filename(NamedOutput);
3935 llvm::sys::path::append(TempPath, OutputFileName);
3936 NamedOutput = C.getArgs().MakeArgString(TempPath.c_str());
3937 }
3938
Chad Rosier62135492012-07-09 17:31:28 +00003939 // If we're saving temps and the temp file conflicts with the input file,
Chad Rosier5b58af02012-04-20 20:05:08 +00003940 // then avoid overwriting input file.
Reid Kleckner68eb60b2015-02-02 22:41:48 +00003941 if (!AtTopLevel && isSaveTempsEnabled() && NamedOutput == BaseName) {
Chad Rosier5b58af02012-04-20 20:05:08 +00003942 bool SameFile = false;
3943 SmallString<256> Result;
3944 llvm::sys::fs::current_path(Result);
3945 llvm::sys::path::append(Result, BaseName);
3946 llvm::sys::fs::equivalent(BaseInput, Result.c_str(), SameFile);
3947 // Must share the same path to conflict.
3948 if (SameFile) {
3949 StringRef Name = llvm::sys::path::filename(BaseInput);
3950 std::pair<StringRef, StringRef> Split = Name.split('.');
Douglas Katzmana67e50c2015-06-26 15:47:46 +00003951 std::string TmpName = GetTemporaryPath(
3952 Split.first, types::getTypeTempSuffix(JA.getType(), IsCLMode()));
Malcolm Parsonsf76f6502016-11-02 10:39:27 +00003953 return C.addTempFile(C.getArgs().MakeArgString(TmpName));
Chad Rosier5b58af02012-04-20 20:05:08 +00003954 }
Chad Rosierf8412cd2011-07-15 21:54:29 +00003955 }
3956
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00003957 // As an annoying special case, PCH generation doesn't strip the pathname.
Nico Weber8ab92192016-03-02 23:29:29 +00003958 if (JA.getType() == types::TY_PCH && !IsCLMode()) {
Michael J. Spencere1696752010-12-18 00:19:12 +00003959 llvm::sys::path::remove_filename(BasePath);
3960 if (BasePath.empty())
Daniel Dunbare6c83192009-03-18 09:58:30 +00003961 BasePath = NamedOutput;
3962 else
Michael J. Spencere1696752010-12-18 00:19:12 +00003963 llvm::sys::path::append(BasePath, NamedOutput);
Chad Rosier633dcdc2013-01-24 19:14:47 +00003964 return C.addResultFile(C.getArgs().MakeArgString(BasePath.c_str()), &JA);
Daniel Dunbar7a178a42009-03-17 17:53:55 +00003965 } else {
Chad Rosier633dcdc2013-01-24 19:14:47 +00003966 return C.addResultFile(NamedOutput, &JA);
Daniel Dunbar7a178a42009-03-17 17:53:55 +00003967 }
3968}
3969
Mehdi Amini12011172016-10-06 05:11:48 +00003970std::string Driver::GetFilePath(StringRef Name, const ToolChain &TC) const {
Chandler Carruth84559242010-03-22 01:52:07 +00003971 // Respect a limited subset of the '-Bprefix' functionality in GCC by
Logan Chiencd679fd2012-10-04 08:08:56 +00003972 // attempting to use this prefix when looking for file paths.
Douglas Katzman26eabf62015-06-24 15:10:30 +00003973 for (const std::string &Dir : PrefixDirs) {
Joerg Sonnenberger6165ab12011-03-21 13:51:29 +00003974 if (Dir.empty())
3975 continue;
Douglas Katzman26eabf62015-06-24 15:10:30 +00003976 SmallString<128> P(Dir[0] == '=' ? SysRoot + Dir.substr(1) : Dir);
Rafael Espindola609a6642013-06-24 18:33:43 +00003977 llvm::sys::path::append(P, Name);
3978 if (llvm::sys::fs::exists(Twine(P)))
Chandler Carruth84559242010-03-22 01:52:07 +00003979 return P.str();
3980 }
3981
Petr Hosek916a4672017-08-10 04:16:38 +00003982 SmallString<128> R(ResourceDir);
3983 llvm::sys::path::append(R, Name);
3984 if (llvm::sys::fs::exists(Twine(R)))
3985 return R.str();
3986
3987 SmallString<128> P(TC.getCompilerRTPath());
Rafael Espindola609a6642013-06-24 18:33:43 +00003988 llvm::sys::path::append(P, Name);
3989 if (llvm::sys::fs::exists(Twine(P)))
Peter Collingbournefa9771f2011-09-06 02:08:31 +00003990 return P.str();
3991
Douglas Katzman26eabf62015-06-24 15:10:30 +00003992 for (const std::string &Dir : TC.getFilePaths()) {
Joerg Sonnenberger6165ab12011-03-21 13:51:29 +00003993 if (Dir.empty())
3994 continue;
Douglas Katzman26eabf62015-06-24 15:10:30 +00003995 SmallString<128> P(Dir[0] == '=' ? SysRoot + Dir.substr(1) : Dir);
Rafael Espindola609a6642013-06-24 18:33:43 +00003996 llvm::sys::path::append(P, Name);
3997 if (llvm::sys::fs::exists(Twine(P)))
Daniel Dunbar1ce81532009-09-09 22:33:00 +00003998 return P.str();
Daniel Dunbar68b01a02009-03-18 20:26:19 +00003999 }
4000
Daniel Dunbar1ce81532009-09-09 22:33:00 +00004001 return Name;
Daniel Dunbar5e0f6af2009-03-13 00:51:18 +00004002}
4003
Douglas Katzmana67e50c2015-06-26 15:47:46 +00004004void Driver::generatePrefixedToolNames(
Mehdi Amini12011172016-10-06 05:11:48 +00004005 StringRef Tool, const ToolChain &TC,
Douglas Katzmana67e50c2015-06-26 15:47:46 +00004006 SmallVectorImpl<std::string> &Names) const {
Saleem Abdulrasoolf0ba6ce2014-10-25 23:33:21 +00004007 // FIXME: Needs a better variable than DefaultTargetTriple
Mehdi Amini12011172016-10-06 05:11:48 +00004008 Names.emplace_back((DefaultTargetTriple + "-" + Tool).str());
Benjamin Kramer3204b152015-05-29 19:42:19 +00004009 Names.emplace_back(Tool);
Vasileios Kalintirisc744e122015-11-12 15:26:54 +00004010
4011 // Allow the discovery of tools prefixed with LLVM's default target triple.
4012 std::string LLVMDefaultTargetTriple = llvm::sys::getDefaultTargetTriple();
4013 if (LLVMDefaultTargetTriple != DefaultTargetTriple)
Mehdi Amini12011172016-10-06 05:11:48 +00004014 Names.emplace_back((LLVMDefaultTargetTriple + "-" + Tool).str());
Saleem Abdulrasoolf0ba6ce2014-10-25 23:33:21 +00004015}
4016
Benjamin Kramer7111b912014-11-04 20:26:01 +00004017static bool ScanDirForExecutable(SmallString<128> &Dir,
4018 ArrayRef<std::string> Names) {
Saleem Abdulrasoolf0ba6ce2014-10-25 23:33:21 +00004019 for (const auto &Name : Names) {
4020 llvm::sys::path::append(Dir, Name);
4021 if (llvm::sys::fs::can_execute(Twine(Dir)))
4022 return true;
4023 llvm::sys::path::remove_filename(Dir);
4024 }
4025 return false;
4026}
4027
Mehdi Amini12011172016-10-06 05:11:48 +00004028std::string Driver::GetProgramPath(StringRef Name, const ToolChain &TC) const {
Saleem Abdulrasoolf0ba6ce2014-10-25 23:33:21 +00004029 SmallVector<std::string, 2> TargetSpecificExecutables;
4030 generatePrefixedToolNames(Name, TC, TargetSpecificExecutables);
4031
Chandler Carruth84559242010-03-22 01:52:07 +00004032 // Respect a limited subset of the '-Bprefix' functionality in GCC by
Logan Chiencd679fd2012-10-04 08:08:56 +00004033 // attempting to use this prefix when looking for program paths.
Saleem Abdulrasool23d99b12014-09-16 03:48:32 +00004034 for (const auto &PrefixDir : PrefixDirs) {
4035 if (llvm::sys::fs::is_directory(PrefixDir)) {
4036 SmallString<128> P(PrefixDir);
Saleem Abdulrasoolf0ba6ce2014-10-25 23:33:21 +00004037 if (ScanDirForExecutable(P, TargetSpecificExecutables))
Rafael Espindola8be5c052013-06-19 13:24:29 +00004038 return P.str();
Simon Atanasyana47ba292012-10-31 14:39:28 +00004039 } else {
Mehdi Amini12011172016-10-06 05:11:48 +00004040 SmallString<128> P((PrefixDir + Name).str());
Rafael Espindola609a6642013-06-24 18:33:43 +00004041 if (llvm::sys::fs::can_execute(Twine(P)))
Rafael Espindola8be5c052013-06-19 13:24:29 +00004042 return P.str();
Simon Atanasyan86bdab72012-10-31 12:01:53 +00004043 }
Chandler Carruth84559242010-03-22 01:52:07 +00004044 }
4045
Daniel Dunbar68b01a02009-03-18 20:26:19 +00004046 const ToolChain::path_list &List = TC.getProgramPaths();
Saleem Abdulrasool23d99b12014-09-16 03:48:32 +00004047 for (const auto &Path : List) {
4048 SmallString<128> P(Path);
Saleem Abdulrasoolf0ba6ce2014-10-25 23:33:21 +00004049 if (ScanDirForExecutable(P, TargetSpecificExecutables))
Rafael Espindola8be5c052013-06-19 13:24:29 +00004050 return P.str();
Daniel Dunbar68b01a02009-03-18 20:26:19 +00004051 }
4052
Daniel Dunbar76ce7412009-03-23 16:15:50 +00004053 // If all else failed, search the path.
Michael J. Spencerb011d482014-11-07 21:30:32 +00004054 for (const auto &TargetSpecificExecutable : TargetSpecificExecutables)
4055 if (llvm::ErrorOr<std::string> P =
4056 llvm::sys::findProgramByName(TargetSpecificExecutable))
Michael J. Spencer04162ea2014-11-04 01:30:55 +00004057 return *P;
Daniel Dunbar6f668772009-03-18 21:34:08 +00004058
Daniel Dunbar1ce81532009-09-09 22:33:00 +00004059 return Name;
Daniel Dunbar5e0f6af2009-03-13 00:51:18 +00004060}
4061
Mehdi Amini12011172016-10-06 05:11:48 +00004062std::string Driver::GetTemporaryPath(StringRef Prefix, StringRef Suffix) const {
Rafael Espindola37d229d2013-06-25 04:26:55 +00004063 SmallString<128> Path;
Rafael Espindolac0809172014-06-12 14:02:15 +00004064 std::error_code EC = llvm::sys::fs::createTemporaryFile(Prefix, Suffix, Path);
Rafael Espindola37d229d2013-06-25 04:26:55 +00004065 if (EC) {
4066 Diag(clang::diag::err_unable_to_make_temp) << EC.message();
Daniel Dunbare627c1c2009-03-18 19:34:39 +00004067 return "";
4068 }
4069
Rafael Espindola37d229d2013-06-25 04:26:55 +00004070 return Path.str();
Daniel Dunbare627c1c2009-03-18 19:34:39 +00004071}
4072
Nico Weber2ca4be92016-03-01 23:16:44 +00004073std::string Driver::GetClPchPath(Compilation &C, StringRef BaseName) const {
4074 SmallString<128> Output;
4075 if (Arg *FpArg = C.getArgs().getLastArg(options::OPT__SLASH_Fp)) {
4076 // FIXME: If anybody needs it, implement this obscure rule:
4077 // "If you specify a directory without a file name, the default file name
4078 // is VCx0.pch., where x is the major version of Visual C++ in use."
4079 Output = FpArg->getValue();
4080
4081 // "If you do not specify an extension as part of the path name, an
4082 // extension of .pch is assumed. "
4083 if (!llvm::sys::path::has_extension(Output))
4084 Output += ".pch";
4085 } else {
4086 Output = BaseName;
4087 llvm::sys::path::replace_extension(Output, ".pch");
4088 }
4089 return Output.str();
4090}
4091
Chandler Carruth2ad5de12012-01-25 11:01:57 +00004092const ToolChain &Driver::getToolChain(const ArgList &Args,
Artem Belevich959e0542015-07-10 19:47:55 +00004093 const llvm::Triple &Target) const {
Chandler Carruth2ad5de12012-01-25 11:01:57 +00004094
David Blaikie6ad71012017-01-13 18:53:43 +00004095 auto &TC = ToolChains[Target.str()];
Chandler Carruth2ad5de12012-01-25 11:01:57 +00004096 if (!TC) {
4097 switch (Target.getOS()) {
Reid Kleckner330fb172016-05-11 16:19:05 +00004098 case llvm::Triple::Haiku:
David Blaikie6ad71012017-01-13 18:53:43 +00004099 TC = llvm::make_unique<toolchains::Haiku>(*this, Target, Args);
Reid Kleckner330fb172016-05-11 16:19:05 +00004100 break;
Ed Schouten4dabea22017-06-25 08:29:09 +00004101 case llvm::Triple::Ananas:
4102 TC = llvm::make_unique<toolchains::Ananas>(*this, Target, Args);
4103 break;
Ed Schouten3c3e58c2015-03-26 11:13:44 +00004104 case llvm::Triple::CloudABI:
David Blaikie6ad71012017-01-13 18:53:43 +00004105 TC = llvm::make_unique<toolchains::CloudABI>(*this, Target, Args);
Ed Schouten3c3e58c2015-03-26 11:13:44 +00004106 break;
Chandler Carruth2ad5de12012-01-25 11:01:57 +00004107 case llvm::Triple::Darwin:
4108 case llvm::Triple::MacOSX:
4109 case llvm::Triple::IOS:
Tim Northover6f3ff222015-10-30 16:30:27 +00004110 case llvm::Triple::TvOS:
4111 case llvm::Triple::WatchOS:
David Blaikie6ad71012017-01-13 18:53:43 +00004112 TC = llvm::make_unique<toolchains::DarwinClang>(*this, Target, Args);
Chandler Carruth2ad5de12012-01-25 11:01:57 +00004113 break;
4114 case llvm::Triple::DragonFly:
David Blaikie6ad71012017-01-13 18:53:43 +00004115 TC = llvm::make_unique<toolchains::DragonFly>(*this, Target, Args);
Chandler Carruth2ad5de12012-01-25 11:01:57 +00004116 break;
4117 case llvm::Triple::OpenBSD:
David Blaikie6ad71012017-01-13 18:53:43 +00004118 TC = llvm::make_unique<toolchains::OpenBSD>(*this, Target, Args);
Chandler Carruth2ad5de12012-01-25 11:01:57 +00004119 break;
4120 case llvm::Triple::NetBSD:
David Blaikie6ad71012017-01-13 18:53:43 +00004121 TC = llvm::make_unique<toolchains::NetBSD>(*this, Target, Args);
Chandler Carruth2ad5de12012-01-25 11:01:57 +00004122 break;
4123 case llvm::Triple::FreeBSD:
David Blaikie6ad71012017-01-13 18:53:43 +00004124 TC = llvm::make_unique<toolchains::FreeBSD>(*this, Target, Args);
Chandler Carruth2ad5de12012-01-25 11:01:57 +00004125 break;
4126 case llvm::Triple::Minix:
David Blaikie6ad71012017-01-13 18:53:43 +00004127 TC = llvm::make_unique<toolchains::Minix>(*this, Target, Args);
Chandler Carruth2ad5de12012-01-25 11:01:57 +00004128 break;
4129 case llvm::Triple::Linux:
Andrey Turetskiy4798eb62016-06-16 10:36:09 +00004130 case llvm::Triple::ELFIAMCU:
Chandler Carruthcf705b22012-01-25 21:03:58 +00004131 if (Target.getArch() == llvm::Triple::hexagon)
David Blaikie6ad71012017-01-13 18:53:43 +00004132 TC = llvm::make_unique<toolchains::HexagonToolChain>(*this, Target,
4133 Args);
Vasileios Kalintirisc744e122015-11-12 15:26:54 +00004134 else if ((Target.getVendor() == llvm::Triple::MipsTechnologies) &&
4135 !Target.hasEnvironment())
David Blaikie6ad71012017-01-13 18:53:43 +00004136 TC = llvm::make_unique<toolchains::MipsLLVMToolChain>(*this, Target,
4137 Args);
Chandler Carruthcf705b22012-01-25 21:03:58 +00004138 else
David Blaikie6ad71012017-01-13 18:53:43 +00004139 TC = llvm::make_unique<toolchains::Linux>(*this, Target, Args);
Chandler Carruth2ad5de12012-01-25 11:01:57 +00004140 break;
Derek Schuff6ab52fa2015-03-30 20:31:33 +00004141 case llvm::Triple::NaCl:
David Blaikie6ad71012017-01-13 18:53:43 +00004142 TC = llvm::make_unique<toolchains::NaClToolChain>(*this, Target, Args);
Derek Schuff6ab52fa2015-03-30 20:31:33 +00004143 break;
Petr Hosek62e1d232016-10-06 06:08:09 +00004144 case llvm::Triple::Fuchsia:
David Blaikie6ad71012017-01-13 18:53:43 +00004145 TC = llvm::make_unique<toolchains::Fuchsia>(*this, Target, Args);
Petr Hosek62e1d232016-10-06 06:08:09 +00004146 break;
David Chisnallf571cde2012-02-15 13:39:01 +00004147 case llvm::Triple::Solaris:
David Blaikie6ad71012017-01-13 18:53:43 +00004148 TC = llvm::make_unique<toolchains::Solaris>(*this, Target, Args);
David Chisnallf571cde2012-02-15 13:39:01 +00004149 break;
Tom Stellard8fa33092015-07-18 01:49:05 +00004150 case llvm::Triple::AMDHSA:
David Blaikie6ad71012017-01-13 18:53:43 +00004151 TC = llvm::make_unique<toolchains::AMDGPUToolChain>(*this, Target, Args);
Tom Stellard8fa33092015-07-18 01:49:05 +00004152 break;
Chandler Carruth2ad5de12012-01-25 11:01:57 +00004153 case llvm::Triple::Win32:
Saleem Abdulrasool377066a2014-03-27 22:50:18 +00004154 switch (Target.getEnvironment()) {
4155 default:
4156 if (Target.isOSBinFormatELF())
David Blaikie6ad71012017-01-13 18:53:43 +00004157 TC = llvm::make_unique<toolchains::Generic_ELF>(*this, Target, Args);
Saleem Abdulrasool377066a2014-03-27 22:50:18 +00004158 else if (Target.isOSBinFormatMachO())
David Blaikie6ad71012017-01-13 18:53:43 +00004159 TC = llvm::make_unique<toolchains::MachO>(*this, Target, Args);
Saleem Abdulrasool377066a2014-03-27 22:50:18 +00004160 else
David Blaikie6ad71012017-01-13 18:53:43 +00004161 TC = llvm::make_unique<toolchains::Generic_GCC>(*this, Target, Args);
Saleem Abdulrasool377066a2014-03-27 22:50:18 +00004162 break;
4163 case llvm::Triple::GNU:
David Blaikie6ad71012017-01-13 18:53:43 +00004164 TC = llvm::make_unique<toolchains::MinGW>(*this, Target, Args);
Saleem Abdulrasool377066a2014-03-27 22:50:18 +00004165 break;
Saleem Abdulrasool543a78b2014-10-24 03:13:37 +00004166 case llvm::Triple::Itanium:
David Blaikie6ad71012017-01-13 18:53:43 +00004167 TC = llvm::make_unique<toolchains::CrossWindowsToolChain>(*this, Target,
4168 Args);
Saleem Abdulrasool543a78b2014-10-24 03:13:37 +00004169 break;
Saleem Abdulrasool377066a2014-03-27 22:50:18 +00004170 case llvm::Triple::MSVC:
4171 case llvm::Triple::UnknownEnvironment:
Dave Leef96bedf2017-11-06 21:18:05 +00004172 if (Args.getLastArgValue(options::OPT_fuse_ld_EQ)
4173 .startswith_lower("bfd"))
4174 TC = llvm::make_unique<toolchains::CrossWindowsToolChain>(
4175 *this, Target, Args);
4176 else
4177 TC =
4178 llvm::make_unique<toolchains::MSVCToolChain>(*this, Target, Args);
Saleem Abdulrasool377066a2014-03-27 22:50:18 +00004179 break;
4180 }
Chandler Carruth2ad5de12012-01-25 11:01:57 +00004181 break;
Filipe Cabecinhasc888e192015-10-14 12:25:43 +00004182 case llvm::Triple::PS4:
David Blaikie6ad71012017-01-13 18:53:43 +00004183 TC = llvm::make_unique<toolchains::PS4CPU>(*this, Target, Args);
Filipe Cabecinhasc888e192015-10-14 12:25:43 +00004184 break;
David L Kreitzerd397ea42016-10-14 20:44:33 +00004185 case llvm::Triple::Contiki:
David Blaikie6ad71012017-01-13 18:53:43 +00004186 TC = llvm::make_unique<toolchains::Contiki>(*this, Target, Args);
David L Kreitzerd397ea42016-10-14 20:44:33 +00004187 break;
Chandler Carruth2ad5de12012-01-25 11:01:57 +00004188 default:
Douglas Katzman9f5e70e2015-05-26 18:01:33 +00004189 // Of these targets, Hexagon is the only one that might have
4190 // an OS of Linux, in which case it got handled above already.
Douglas Katzman15a63ed2015-08-12 18:36:12 +00004191 switch (Target.getArch()) {
4192 case llvm::Triple::tce:
David Blaikie6ad71012017-01-13 18:53:43 +00004193 TC = llvm::make_unique<toolchains::TCEToolChain>(*this, Target, Args);
Douglas Katzman15a63ed2015-08-12 18:36:12 +00004194 break;
Pekka Jaaskelainen67354482016-11-16 15:22:31 +00004195 case llvm::Triple::tcele:
David Blaikie6ad71012017-01-13 18:53:43 +00004196 TC = llvm::make_unique<toolchains::TCELEToolChain>(*this, Target, Args);
Pekka Jaaskelainen67354482016-11-16 15:22:31 +00004197 break;
Douglas Katzman15a63ed2015-08-12 18:36:12 +00004198 case llvm::Triple::hexagon:
David Blaikie6ad71012017-01-13 18:53:43 +00004199 TC = llvm::make_unique<toolchains::HexagonToolChain>(*this, Target,
4200 Args);
Douglas Katzman15a63ed2015-08-12 18:36:12 +00004201 break;
Jacques Pienaard964cc22016-03-28 21:02:54 +00004202 case llvm::Triple::lanai:
David Blaikie6ad71012017-01-13 18:53:43 +00004203 TC = llvm::make_unique<toolchains::LanaiToolChain>(*this, Target, Args);
Jacques Pienaard964cc22016-03-28 21:02:54 +00004204 break;
Douglas Katzman15a63ed2015-08-12 18:36:12 +00004205 case llvm::Triple::xcore:
David Blaikie6ad71012017-01-13 18:53:43 +00004206 TC = llvm::make_unique<toolchains::XCoreToolChain>(*this, Target, Args);
Douglas Katzman15a63ed2015-08-12 18:36:12 +00004207 break;
Dan Gohmanc2853072015-09-03 22:51:53 +00004208 case llvm::Triple::wasm32:
4209 case llvm::Triple::wasm64:
David Blaikie6ad71012017-01-13 18:53:43 +00004210 TC = llvm::make_unique<toolchains::WebAssembly>(*this, Target, Args);
Dan Gohmanc2853072015-09-03 22:51:53 +00004211 break;
Dylan McKay924fa3a2017-01-05 05:20:27 +00004212 case llvm::Triple::avr:
David Blaikie6ad71012017-01-13 18:53:43 +00004213 TC = llvm::make_unique<toolchains::AVRToolChain>(*this, Target, Args);
Dylan McKay924fa3a2017-01-05 05:20:27 +00004214 break;
Douglas Katzman15a63ed2015-08-12 18:36:12 +00004215 default:
Douglas Katzmand6e597c2015-09-17 19:56:40 +00004216 if (Target.getVendor() == llvm::Triple::Myriad)
David Blaikie6ad71012017-01-13 18:53:43 +00004217 TC = llvm::make_unique<toolchains::MyriadToolChain>(*this, Target,
4218 Args);
Jonathan Roelofs901c7762017-05-25 15:42:13 +00004219 else if (toolchains::BareMetal::handlesTarget(Target))
4220 TC = llvm::make_unique<toolchains::BareMetal>(*this, Target, Args);
Douglas Katzmand6e597c2015-09-17 19:56:40 +00004221 else if (Target.isOSBinFormatELF())
David Blaikie6ad71012017-01-13 18:53:43 +00004222 TC = llvm::make_unique<toolchains::Generic_ELF>(*this, Target, Args);
Douglas Katzman15a63ed2015-08-12 18:36:12 +00004223 else if (Target.isOSBinFormatMachO())
David Blaikie6ad71012017-01-13 18:53:43 +00004224 TC = llvm::make_unique<toolchains::MachO>(*this, Target, Args);
Douglas Katzman15a63ed2015-08-12 18:36:12 +00004225 else
David Blaikie6ad71012017-01-13 18:53:43 +00004226 TC = llvm::make_unique<toolchains::Generic_GCC>(*this, Target, Args);
Douglas Katzman15a63ed2015-08-12 18:36:12 +00004227 }
Chandler Carruth2ad5de12012-01-25 11:01:57 +00004228 }
4229 }
Justin Lebar66c4fd72016-11-18 00:41:22 +00004230
4231 // Intentionally omitted from the switch above: llvm::Triple::CUDA. CUDA
4232 // compiles always need two toolchains, the CUDA toolchain and the host
4233 // toolchain. So the only valid way to create a CUDA toolchain is via
4234 // CreateOffloadingDeviceToolChains.
4235
Chandler Carruth2ad5de12012-01-25 11:01:57 +00004236 return *TC;
Daniel Dunbar4dff6a42009-03-10 23:41:59 +00004237}
Daniel Dunbar8fa879d2009-03-24 18:57:02 +00004238
Rafael Espindola2f69d402013-03-18 15:33:26 +00004239bool Driver::ShouldUseClangCompiler(const JobAction &JA) const {
Douglas Katzman00249092015-06-12 15:45:21 +00004240 // Say "no" if there is not exactly one input of a type clang understands.
Nico Weber5a459f82016-02-23 19:30:43 +00004241 if (JA.size() != 1 ||
4242 !types::isAcceptedByClang((*JA.input_begin())->getType()))
Nick Lewycky5cc9ebb2012-11-15 05:36:36 +00004243 return false;
4244
Douglas Katzman00249092015-06-12 15:45:21 +00004245 // And say "no" if this is not a kind of action clang understands.
Nick Lewycky5cc9ebb2012-11-15 05:36:36 +00004246 if (!isa<PreprocessJobAction>(JA) && !isa<PrecompileJobAction>(JA) &&
Bob Wilson23a55f12014-12-21 07:00:00 +00004247 !isa<CompileJobAction>(JA) && !isa<BackendJobAction>(JA))
Nick Lewycky5cc9ebb2012-11-15 05:36:36 +00004248 return false;
4249
4250 return true;
4251}
4252
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00004253/// GetReleaseVersion - Parse (([0-9]+)(.([0-9]+)(.([0-9]+)?))?)? and return the
4254/// grouped values as integers. Numbers which are not provided are set to 0.
Daniel Dunbarc7fd57a2009-03-26 15:58:36 +00004255///
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00004256/// \return True if the entire string was parsed (9.2), or all groups were
4257/// parsed (10.3.5extrastuff).
Mehdi Amini12011172016-10-06 05:11:48 +00004258bool Driver::GetReleaseVersion(StringRef Str, unsigned &Major, unsigned &Minor,
4259 unsigned &Micro, bool &HadExtra) {
Daniel Dunbarc7fd57a2009-03-26 15:58:36 +00004260 HadExtra = false;
4261
4262 Major = Minor = Micro = 0;
Mehdi Amini12011172016-10-06 05:11:48 +00004263 if (Str.empty())
Bob Wilson433cb312015-04-07 01:03:35 +00004264 return false;
Daniel Dunbarc7fd57a2009-03-26 15:58:36 +00004265
Mehdi Amini12011172016-10-06 05:11:48 +00004266 if (Str.consumeInteger(10, Major))
4267 return false;
4268 if (Str.empty())
Daniel Dunbarc7fd57a2009-03-26 15:58:36 +00004269 return true;
Mehdi Amini12011172016-10-06 05:11:48 +00004270 if (Str[0] != '.')
Daniel Dunbarc7fd57a2009-03-26 15:58:36 +00004271 return false;
Daniel Dunbarf26a7ab2009-09-08 23:36:43 +00004272
Mehdi Amini12011172016-10-06 05:11:48 +00004273 Str = Str.drop_front(1);
Daniel Dunbarc7fd57a2009-03-26 15:58:36 +00004274
Mehdi Amini12011172016-10-06 05:11:48 +00004275 if (Str.consumeInteger(10, Minor))
Daniel Dunbarc7fd57a2009-03-26 15:58:36 +00004276 return false;
Mehdi Amini12011172016-10-06 05:11:48 +00004277 if (Str.empty())
4278 return true;
4279 if (Str[0] != '.')
4280 return false;
4281 Str = Str.drop_front(1);
4282
4283 if (Str.consumeInteger(10, Micro))
4284 return false;
4285 if (!Str.empty())
4286 HadExtra = true;
Daniel Dunbarc7fd57a2009-03-26 15:58:36 +00004287 return true;
4288}
Hans Wennborg6ddc6902013-07-27 00:23:45 +00004289
Bruno Cardoso Lopes8ed5cac2016-03-31 02:45:46 +00004290/// Parse digits from a string \p Str and fulfill \p Digits with
4291/// the parsed numbers. This method assumes that the max number of
4292/// digits to look for is equal to Digits.size().
4293///
4294/// \return True if the entire string was parsed and there are
4295/// no extra characters remaining at the end.
Mehdi Amini12011172016-10-06 05:11:48 +00004296bool Driver::GetReleaseVersion(StringRef Str,
Bruno Cardoso Lopes8ed5cac2016-03-31 02:45:46 +00004297 MutableArrayRef<unsigned> Digits) {
Mehdi Amini12011172016-10-06 05:11:48 +00004298 if (Str.empty())
Bruno Cardoso Lopes8ed5cac2016-03-31 02:45:46 +00004299 return false;
4300
Bruno Cardoso Lopes8ed5cac2016-03-31 02:45:46 +00004301 unsigned CurDigit = 0;
4302 while (CurDigit < Digits.size()) {
Mehdi Amini12011172016-10-06 05:11:48 +00004303 unsigned Digit;
4304 if (Str.consumeInteger(10, Digit))
Bruno Cardoso Lopes8ed5cac2016-03-31 02:45:46 +00004305 return false;
Mehdi Amini12011172016-10-06 05:11:48 +00004306 Digits[CurDigit] = Digit;
4307 if (Str.empty())
4308 return true;
4309 if (Str[0] != '.')
4310 return false;
4311 Str = Str.drop_front(1);
Bruno Cardoso Lopes8ed5cac2016-03-31 02:45:46 +00004312 CurDigit++;
4313 }
4314
4315 // More digits than requested, bail out...
4316 return false;
4317}
4318
Hans Wennborg6ddc6902013-07-27 00:23:45 +00004319std::pair<unsigned, unsigned> Driver::getIncludeExcludeOptionFlagMasks() const {
4320 unsigned IncludedFlagsBitmask = 0;
Rafael Espindolacc707bc2013-09-25 15:54:41 +00004321 unsigned ExcludedFlagsBitmask = options::NoDriverOption;
Hans Wennborg6ddc6902013-07-27 00:23:45 +00004322
4323 if (Mode == CLMode) {
Hans Wennborg19076102013-07-31 20:51:53 +00004324 // Include CL and Core options.
4325 IncludedFlagsBitmask |= options::CLOption;
4326 IncludedFlagsBitmask |= options::CoreOption;
Hans Wennborg6ddc6902013-07-27 00:23:45 +00004327 } else {
4328 ExcludedFlagsBitmask |= options::CLOption;
4329 }
4330
4331 return std::make_pair(IncludedFlagsBitmask, ExcludedFlagsBitmask);
4332}
Benjamin Kramerab88f622014-03-25 18:02:07 +00004333
Douglas Katzmanf08fadf2015-06-04 14:40:44 +00004334bool clang::driver::isOptimizationLevelFast(const ArgList &Args) {
Benjamin Kramerab88f622014-03-25 18:02:07 +00004335 return Args.hasFlag(options::OPT_Ofast, options::OPT_O_Group, false);
4336}