blob: 605885239edb93a05dee777dfdb50fd313cedf27 [file] [log] [blame]
Daniel Dunbar2fcaa542010-05-20 17:49:16 +00001//===-- cc1as_main.cpp - Clang Assembler ---------------------------------===//
2//
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//
10// This is the entry point to the clang -cc1as functionality, which implements
11// the direct interface to the LLVM MC based assembler.
12//
13//===----------------------------------------------------------------------===//
14
15#include "clang/Basic/Diagnostic.h"
Chandler Carruthcc0694c2012-12-04 09:25:21 +000016#include "clang/Basic/DiagnosticOptions.h"
Chandler Carruthcc0694c2012-12-04 09:25:21 +000017#include "clang/Driver/DriverDiagnostic.h"
Daniel Dunbar2fcaa542010-05-20 17:49:16 +000018#include "clang/Driver/Options.h"
Daniel Dunbar2fcaa542010-05-20 17:49:16 +000019#include "clang/Frontend/FrontendDiagnostic.h"
20#include "clang/Frontend/TextDiagnosticPrinter.h"
Reid Kleckner898229a2013-06-14 17:17:23 +000021#include "clang/Frontend/Utils.h"
Rafael Espindola4dedcd72015-04-09 21:06:11 +000022#include "llvm/ADT/STLExtras.h"
Daniel Dunbar2fcaa542010-05-20 17:49:16 +000023#include "llvm/ADT/StringSwitch.h"
Duncan Sandsf610b5b2010-08-30 09:42:39 +000024#include "llvm/ADT/Triple.h"
Chandler Carruthffd55512013-01-02 11:45:17 +000025#include "llvm/IR/DataLayout.h"
Chandler Carruthcc0694c2012-12-04 09:25:21 +000026#include "llvm/MC/MCAsmBackend.h"
Daniel Dunbar05474282010-07-17 02:26:21 +000027#include "llvm/MC/MCAsmInfo.h"
Daniel Dunbar2fcaa542010-05-20 17:49:16 +000028#include "llvm/MC/MCCodeEmitter.h"
29#include "llvm/MC/MCContext.h"
Evan Cheng279f2902011-07-11 04:24:19 +000030#include "llvm/MC/MCInstrInfo.h"
Evan Cheng347033f2011-07-20 06:22:27 +000031#include "llvm/MC/MCObjectFileInfo.h"
Peter Collingbournef7b81db2018-05-18 18:26:45 +000032#include "llvm/MC/MCObjectWriter.h"
Chandler Carruthcc0694c2012-12-04 09:25:21 +000033#include "llvm/MC/MCParser/MCAsmParser.h"
Benjamin Kramer5e456302016-01-27 10:01:30 +000034#include "llvm/MC/MCParser/MCTargetAsmParser.h"
Evan Chengb505ace2011-07-18 20:57:51 +000035#include "llvm/MC/MCRegisterInfo.h"
Daniel Dunbar2fcaa542010-05-20 17:49:16 +000036#include "llvm/MC/MCStreamer.h"
Evan Chengdec31872011-07-09 06:04:17 +000037#include "llvm/MC/MCSubtargetInfo.h"
Evgeniy Stepanoveeb820f2014-04-23 11:15:49 +000038#include "llvm/MC/MCTargetOptions.h"
Reid Kleckner898229a2013-06-14 17:17:23 +000039#include "llvm/Option/Arg.h"
40#include "llvm/Option/ArgList.h"
41#include "llvm/Option/OptTable.h"
Daniel Dunbar0454f652010-05-20 18:15:20 +000042#include "llvm/Support/CommandLine.h"
Daniel Dunbar2fcaa542010-05-20 17:49:16 +000043#include "llvm/Support/ErrorHandling.h"
Rafael Espindolaccc6ea62013-06-26 12:48:34 +000044#include "llvm/Support/FileSystem.h"
Chandler Carruthcc0694c2012-12-04 09:25:21 +000045#include "llvm/Support/FormattedStream.h"
46#include "llvm/Support/Host.h"
Daniel Dunbar2fcaa542010-05-20 17:49:16 +000047#include "llvm/Support/MemoryBuffer.h"
Michael J. Spencer8aaf4992010-11-29 18:12:39 +000048#include "llvm/Support/Path.h"
49#include "llvm/Support/Signals.h"
Chandler Carruthcc0694c2012-12-04 09:25:21 +000050#include "llvm/Support/SourceMgr.h"
Evan Cheng494eb062011-08-24 18:09:14 +000051#include "llvm/Support/TargetRegistry.h"
52#include "llvm/Support/TargetSelect.h"
53#include "llvm/Support/Timer.h"
54#include "llvm/Support/raw_ostream.h"
Ahmed Charlesdfca6f92014-03-09 11:36:40 +000055#include <memory>
Rafael Espindola8a8e5542014-06-12 17:19:42 +000056#include <system_error>
Daniel Dunbar2fcaa542010-05-20 17:49:16 +000057using namespace clang;
58using namespace clang::driver;
Alp Toker61dad752014-07-09 14:05:11 +000059using namespace clang::driver::options;
Daniel Dunbar2fcaa542010-05-20 17:49:16 +000060using namespace llvm;
Reid Kleckner898229a2013-06-14 17:17:23 +000061using namespace llvm::opt;
Daniel Dunbar2fcaa542010-05-20 17:49:16 +000062
63namespace {
64
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000065/// Helper class for representing a single invocation of the assembler.
Daniel Dunbar2fcaa542010-05-20 17:49:16 +000066struct AssemblerInvocation {
67 /// @name Target Options
68 /// @{
69
Jim Grosbach576452b2012-02-10 20:37:10 +000070 /// The name of the target triple to assemble for.
Daniel Dunbar2fcaa542010-05-20 17:49:16 +000071 std::string Triple;
72
Jim Grosbach576452b2012-02-10 20:37:10 +000073 /// If given, the name of the target CPU to determine which instructions
74 /// are legal.
75 std::string CPU;
76
77 /// The list of target specific features to enable or disable -- this should
78 /// be a list of strings starting with '+' or '-'.
79 std::vector<std::string> Features;
80
Mandeep Singh Grang358faec2016-12-01 18:42:16 +000081 /// The list of symbol definitions.
82 std::vector<std::string> SymbolDefs;
83
Daniel Dunbar2fcaa542010-05-20 17:49:16 +000084 /// @}
85 /// @name Language Options
86 /// @{
87
88 std::vector<std::string> IncludePaths;
89 unsigned NoInitialTextSection : 1;
Daniel Dunbar9cf7bc72011-03-28 22:49:24 +000090 unsigned SaveTemporaryLabels : 1;
Kevin Enderby292dc082011-12-22 19:31:58 +000091 unsigned GenDwarfForAssembly : 1;
Rafael Espindolaf8f01c32016-05-29 02:01:14 +000092 unsigned RelaxELFRelocations : 1;
Oliver Stannard9b2a7d42014-05-19 13:39:13 +000093 unsigned DwarfVersion;
Kevin Enderby292dc082011-12-22 19:31:58 +000094 std::string DwarfDebugFlags;
Kevin Enderbyae2ec472013-01-17 21:38:06 +000095 std::string DwarfDebugProducer;
Chandler Carruth4d5e1a92012-12-17 21:40:04 +000096 std::string DebugCompilationDir;
Saleem Abdulrasool54448902017-06-09 00:40:30 +000097 llvm::DebugCompressionType CompressDebugSections =
98 llvm::DebugCompressionType::None;
Eric Christopher45f2e712012-12-18 00:31:10 +000099 std::string MainFileName;
Daniel Dunbar2fcaa542010-05-20 17:49:16 +0000100
101 /// @}
102 /// @name Frontend Options
103 /// @{
104
105 std::string InputFile;
Daniel Dunbar0454f652010-05-20 18:15:20 +0000106 std::vector<std::string> LLVMArgs;
Daniel Dunbar2fcaa542010-05-20 17:49:16 +0000107 std::string OutputPath;
108 enum FileType {
109 FT_Asm, ///< Assembly (.s) output, transliterate mode.
110 FT_Null, ///< No output, for timing purposes.
111 FT_Obj ///< Object file output.
112 };
113 FileType OutputType;
Daniel Dunbar0454f652010-05-20 18:15:20 +0000114 unsigned ShowHelp : 1;
115 unsigned ShowVersion : 1;
Daniel Dunbar2fcaa542010-05-20 17:49:16 +0000116
117 /// @}
118 /// @name Transliterate Options
119 /// @{
120
121 unsigned OutputAsmVariant;
122 unsigned ShowEncoding : 1;
123 unsigned ShowInst : 1;
124
125 /// @}
126 /// @name Assembler Options
127 /// @{
128
129 unsigned RelaxAll : 1;
Rafael Espindola148141c2011-01-23 17:58:26 +0000130 unsigned NoExecStack : 1;
Joerg Sonnenbergera43604a2014-08-26 18:40:25 +0000131 unsigned FatalWarnings : 1;
David Majnemer2b9349d2015-12-21 22:09:34 +0000132 unsigned IncrementalLinkerCompatible : 1;
Daniel Dunbar2fcaa542010-05-20 17:49:16 +0000133
Joerg Sonnenberger924f6ad2015-09-18 11:13:43 +0000134 /// The name of the relocation model to use.
135 std::string RelocationModel;
136
Daniel Dunbar2fcaa542010-05-20 17:49:16 +0000137 /// @}
138
139public:
140 AssemblerInvocation() {
141 Triple = "";
142 NoInitialTextSection = 0;
143 InputFile = "-";
Daniel Dunbar0454f652010-05-20 18:15:20 +0000144 OutputPath = "-";
Daniel Dunbar2fcaa542010-05-20 17:49:16 +0000145 OutputType = FT_Asm;
146 OutputAsmVariant = 0;
147 ShowInst = 0;
148 ShowEncoding = 0;
149 RelaxAll = 0;
Rafael Espindola148141c2011-01-23 17:58:26 +0000150 NoExecStack = 0;
Joerg Sonnenbergera43604a2014-08-26 18:40:25 +0000151 FatalWarnings = 0;
David Majnemer2b9349d2015-12-21 22:09:34 +0000152 IncrementalLinkerCompatible = 0;
Douglas Katzman722bcb02015-10-13 16:22:51 +0000153 DwarfVersion = 0;
Daniel Dunbar2fcaa542010-05-20 17:49:16 +0000154 }
155
Sean Silva070cd2d2014-08-15 21:38:36 +0000156 static bool CreateFromArgs(AssemblerInvocation &Res,
157 ArrayRef<const char *> Argv,
158 DiagnosticsEngine &Diags);
Daniel Dunbar2fcaa542010-05-20 17:49:16 +0000159};
160
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000161}
Daniel Dunbar2fcaa542010-05-20 17:49:16 +0000162
Dylan Noblesmithe99b27f2011-12-23 03:05:38 +0000163bool AssemblerInvocation::CreateFromArgs(AssemblerInvocation &Opts,
Sean Silva070cd2d2014-08-15 21:38:36 +0000164 ArrayRef<const char *> Argv,
David Blaikie9c902b52011-09-25 23:23:43 +0000165 DiagnosticsEngine &Diags) {
Dylan Noblesmithe99b27f2011-12-23 03:05:38 +0000166 bool Success = true;
167
Daniel Dunbar2fcaa542010-05-20 17:49:16 +0000168 // Parse the arguments.
Alp Toker61dad752014-07-09 14:05:11 +0000169 std::unique_ptr<OptTable> OptTbl(createDriverOptTable());
170
171 const unsigned IncludedFlagsBitmask = options::CC1AsOption;
Daniel Dunbar2fcaa542010-05-20 17:49:16 +0000172 unsigned MissingArgIndex, MissingArgCount;
David Blaikie69a1d8c2015-06-22 22:07:27 +0000173 InputArgList Args = OptTbl->ParseArgs(Argv, MissingArgIndex, MissingArgCount,
174 IncludedFlagsBitmask);
Daniel Dunbar2fcaa542010-05-20 17:49:16 +0000175
176 // Check for missing argument error.
Dylan Noblesmithe99b27f2011-12-23 03:05:38 +0000177 if (MissingArgCount) {
Daniel Dunbar2fcaa542010-05-20 17:49:16 +0000178 Diags.Report(diag::err_drv_missing_argument)
David Blaikie69a1d8c2015-06-22 22:07:27 +0000179 << Args.getArgString(MissingArgIndex) << MissingArgCount;
Dylan Noblesmithe99b27f2011-12-23 03:05:38 +0000180 Success = false;
181 }
Daniel Dunbar2fcaa542010-05-20 17:49:16 +0000182
183 // Issue errors on unknown arguments.
David Blaikie69a1d8c2015-06-22 22:07:27 +0000184 for (const Arg *A : Args.filtered(OPT_UNKNOWN)) {
Brian Gesiakceb987f2018-01-13 17:09:11 +0000185 auto ArgString = A->getAsString(Args);
186 std::string Nearest;
187 if (OptTbl->findNearest(ArgString, Nearest, IncludedFlagsBitmask) > 1)
188 Diags.Report(diag::err_drv_unknown_argument) << ArgString;
189 else
190 Diags.Report(diag::err_drv_unknown_argument_with_suggestion)
191 << ArgString << Nearest;
Dylan Noblesmithe99b27f2011-12-23 03:05:38 +0000192 Success = false;
193 }
Daniel Dunbar2fcaa542010-05-20 17:49:16 +0000194
195 // Construct the invocation.
196
197 // Target Options
David Blaikie69a1d8c2015-06-22 22:07:27 +0000198 Opts.Triple = llvm::Triple::normalize(Args.getLastArgValue(OPT_triple));
199 Opts.CPU = Args.getLastArgValue(OPT_target_cpu);
200 Opts.Features = Args.getAllArgValues(OPT_target_feature);
Jim Grosbach576452b2012-02-10 20:37:10 +0000201
202 // Use the default target triple if unspecified.
203 if (Opts.Triple.empty())
204 Opts.Triple = llvm::sys::getDefaultTargetTriple();
Daniel Dunbar2fcaa542010-05-20 17:49:16 +0000205
206 // Language Options
David Blaikie69a1d8c2015-06-22 22:07:27 +0000207 Opts.IncludePaths = Args.getAllArgValues(OPT_I);
208 Opts.NoInitialTextSection = Args.hasArg(OPT_n);
209 Opts.SaveTemporaryLabels = Args.hasArg(OPT_msave_temp_labels);
Douglas Katzman3459ce22015-10-08 04:24:12 +0000210 // Any DebugInfoKind implies GenDwarfForAssembly.
211 Opts.GenDwarfForAssembly = Args.hasArg(OPT_debug_info_kind_EQ);
Saleem Abdulrasoold064e912017-06-23 15:34:16 +0000212
213 if (const Arg *A = Args.getLastArg(OPT_compress_debug_sections,
214 OPT_compress_debug_sections_EQ)) {
215 if (A->getOption().getID() == OPT_compress_debug_sections) {
216 // TODO: be more clever about the compression type auto-detection
217 Opts.CompressDebugSections = llvm::DebugCompressionType::GNU;
218 } else {
219 Opts.CompressDebugSections =
220 llvm::StringSwitch<llvm::DebugCompressionType>(A->getValue())
221 .Case("none", llvm::DebugCompressionType::None)
222 .Case("zlib", llvm::DebugCompressionType::Z)
223 .Case("zlib-gnu", llvm::DebugCompressionType::GNU)
224 .Default(llvm::DebugCompressionType::None);
225 }
226 }
227
Rafael Espindolaf8f01c32016-05-29 02:01:14 +0000228 Opts.RelaxELFRelocations = Args.hasArg(OPT_mrelax_relocations);
Adrian Prantlae39ccc2016-04-19 20:31:19 +0000229 Opts.DwarfVersion = getLastArgIntValue(Args, OPT_dwarf_version_EQ, 2, Diags);
David Blaikie69a1d8c2015-06-22 22:07:27 +0000230 Opts.DwarfDebugFlags = Args.getLastArgValue(OPT_dwarf_debug_flags);
231 Opts.DwarfDebugProducer = Args.getLastArgValue(OPT_dwarf_debug_producer);
232 Opts.DebugCompilationDir = Args.getLastArgValue(OPT_fdebug_compilation_dir);
233 Opts.MainFileName = Args.getLastArgValue(OPT_main_file_name);
Daniel Dunbar2fcaa542010-05-20 17:49:16 +0000234
235 // Frontend Options
David Blaikie69a1d8c2015-06-22 22:07:27 +0000236 if (Args.hasArg(OPT_INPUT)) {
Daniel Dunbar2fcaa542010-05-20 17:49:16 +0000237 bool First = true;
Richard Smith0aef3052017-02-18 01:14:43 +0000238 for (const Arg *A : Args.filtered(OPT_INPUT)) {
239 if (First) {
Richard Smithbd55daf2012-11-01 04:30:05 +0000240 Opts.InputFile = A->getValue();
Richard Smith0aef3052017-02-18 01:14:43 +0000241 First = false;
242 } else {
David Blaikie69a1d8c2015-06-22 22:07:27 +0000243 Diags.Report(diag::err_drv_unknown_argument) << A->getAsString(Args);
Dylan Noblesmithe99b27f2011-12-23 03:05:38 +0000244 Success = false;
245 }
Daniel Dunbar2fcaa542010-05-20 17:49:16 +0000246 }
247 }
David Blaikie69a1d8c2015-06-22 22:07:27 +0000248 Opts.LLVMArgs = Args.getAllArgValues(OPT_mllvm);
249 Opts.OutputPath = Args.getLastArgValue(OPT_o);
250 if (Arg *A = Args.getLastArg(OPT_filetype)) {
Richard Smithbd55daf2012-11-01 04:30:05 +0000251 StringRef Name = A->getValue();
Daniel Dunbar2fcaa542010-05-20 17:49:16 +0000252 unsigned OutputType = StringSwitch<unsigned>(Name)
253 .Case("asm", FT_Asm)
254 .Case("null", FT_Null)
255 .Case("obj", FT_Obj)
256 .Default(~0U);
Dylan Noblesmithe99b27f2011-12-23 03:05:38 +0000257 if (OutputType == ~0U) {
David Blaikie69a1d8c2015-06-22 22:07:27 +0000258 Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << Name;
Dylan Noblesmithe99b27f2011-12-23 03:05:38 +0000259 Success = false;
260 } else
Daniel Dunbar2fcaa542010-05-20 17:49:16 +0000261 Opts.OutputType = FileType(OutputType);
262 }
David Blaikie69a1d8c2015-06-22 22:07:27 +0000263 Opts.ShowHelp = Args.hasArg(OPT_help);
264 Opts.ShowVersion = Args.hasArg(OPT_version);
Daniel Dunbar2fcaa542010-05-20 17:49:16 +0000265
266 // Transliterate Options
Reid Kleckner898229a2013-06-14 17:17:23 +0000267 Opts.OutputAsmVariant =
David Blaikie69a1d8c2015-06-22 22:07:27 +0000268 getLastArgIntValue(Args, OPT_output_asm_variant, 0, Diags);
269 Opts.ShowEncoding = Args.hasArg(OPT_show_encoding);
270 Opts.ShowInst = Args.hasArg(OPT_show_inst);
Daniel Dunbar2fcaa542010-05-20 17:49:16 +0000271
272 // Assemble Options
David Blaikie69a1d8c2015-06-22 22:07:27 +0000273 Opts.RelaxAll = Args.hasArg(OPT_mrelax_all);
274 Opts.NoExecStack = Args.hasArg(OPT_mno_exec_stack);
275 Opts.FatalWarnings = Args.hasArg(OPT_massembler_fatal_warnings);
Joerg Sonnenberger924f6ad2015-09-18 11:13:43 +0000276 Opts.RelocationModel = Args.getLastArgValue(OPT_mrelocation_model, "pic");
David Majnemer2b9349d2015-12-21 22:09:34 +0000277 Opts.IncrementalLinkerCompatible =
278 Args.hasArg(OPT_mincremental_linker_compatible);
Mandeep Singh Grang358faec2016-12-01 18:42:16 +0000279 Opts.SymbolDefs = Args.getAllArgValues(OPT_defsym);
Dylan Noblesmithe99b27f2011-12-23 03:05:38 +0000280
Dylan Noblesmith68207c02011-12-26 19:29:47 +0000281 return Success;
Daniel Dunbar2fcaa542010-05-20 17:49:16 +0000282}
283
Rafael Espindola7e556ad2015-04-09 21:50:11 +0000284static std::unique_ptr<raw_fd_ostream>
Amara Emersonf528bcc2018-05-22 11:18:58 +0000285getOutputStream(AssemblerInvocation &Opts, DiagnosticsEngine &Diags,
286 bool Binary) {
287 if (Opts.OutputPath.empty())
288 Opts.OutputPath = "-";
289
Daniel Dunbar2fcaa542010-05-20 17:49:16 +0000290 // Make sure that the Out file gets unlinked from the disk if we get a
291 // SIGINT.
Amara Emersonf528bcc2018-05-22 11:18:58 +0000292 if (Opts.OutputPath != "-")
293 sys::RemoveFileOnSignal(Opts.OutputPath);
Daniel Dunbar2fcaa542010-05-20 17:49:16 +0000294
Rafael Espindoladae941a2014-08-25 18:17:04 +0000295 std::error_code EC;
Rafael Espindola7e556ad2015-04-09 21:50:11 +0000296 auto Out = llvm::make_unique<raw_fd_ostream>(
Amara Emersonf528bcc2018-05-22 11:18:58 +0000297 Opts.OutputPath, EC, (Binary ? sys::fs::F_None : sys::fs::F_Text));
Rafael Espindoladae941a2014-08-25 18:17:04 +0000298 if (EC) {
Amara Emersonf528bcc2018-05-22 11:18:58 +0000299 Diags.Report(diag::err_fe_unable_to_open_output) << Opts.OutputPath
300 << EC.message();
Craig Topper69186e72014-06-08 08:38:04 +0000301 return nullptr;
Daniel Dunbar2fcaa542010-05-20 17:49:16 +0000302 }
303
Rafael Espindola4dedcd72015-04-09 21:06:11 +0000304 return Out;
Daniel Dunbar2fcaa542010-05-20 17:49:16 +0000305}
306
David Blaikie9c902b52011-09-25 23:23:43 +0000307static bool ExecuteAssembler(AssemblerInvocation &Opts,
308 DiagnosticsEngine &Diags) {
Daniel Dunbar2fcaa542010-05-20 17:49:16 +0000309 // Get the target specific parser.
310 std::string Error;
Alp Tokere98ea7c2014-05-31 00:02:21 +0000311 const Target *TheTarget = TargetRegistry::lookupTarget(Opts.Triple, Error);
Alp Toker44293142014-05-31 00:02:27 +0000312 if (!TheTarget)
313 return Diags.Report(diag::err_target_unknown_triple) << Opts.Triple;
Daniel Dunbar2fcaa542010-05-20 17:49:16 +0000314
Rafael Espindola2d2b4202014-07-06 17:43:24 +0000315 ErrorOr<std::unique_ptr<MemoryBuffer>> Buffer =
316 MemoryBuffer::getFileOrSTDIN(Opts.InputFile);
317
318 if (std::error_code EC = Buffer.getError()) {
319 Error = EC.message();
Alp Toker44293142014-05-31 00:02:27 +0000320 return Diags.Report(diag::err_fe_error_reading) << Opts.InputFile;
Daniel Dunbar2fcaa542010-05-20 17:49:16 +0000321 }
322
323 SourceMgr SrcMgr;
324
325 // Tell SrcMgr about this buffer, which is what the parser will pick up.
David Blaikie9e095d92014-08-21 21:01:00 +0000326 SrcMgr.AddNewSourceBuffer(std::move(*Buffer), SMLoc());
Daniel Dunbar2fcaa542010-05-20 17:49:16 +0000327
328 // Record the location of the include directories so that the lexer can find
329 // it later.
330 SrcMgr.setIncludeDirs(Opts.IncludePaths);
331
Ahmed Charlesb8984322014-03-07 20:03:18 +0000332 std::unique_ptr<MCRegisterInfo> MRI(TheTarget->createMCRegInfo(Opts.Triple));
Evan Chengb505ace2011-07-18 20:57:51 +0000333 assert(MRI && "Unable to create target register info!");
334
Ahmed Charlesb8984322014-03-07 20:03:18 +0000335 std::unique_ptr<MCAsmInfo> MAI(TheTarget->createMCAsmInfo(*MRI, Opts.Triple));
Rafael Espindola77056232013-05-13 01:24:18 +0000336 assert(MAI && "Unable to create target asm info!");
337
David Blaikieb31e1d12014-03-31 23:47:13 +0000338 // Ensure MCAsmInfo initialization occurs before any use, otherwise sections
339 // may be created with a combination of default and explicit settings.
Saleem Abdulrasool54448902017-06-09 00:40:30 +0000340 MAI->setCompressDebugSections(Opts.CompressDebugSections);
David Blaikieb31e1d12014-03-31 23:47:13 +0000341
Rafael Espindolaf8f01c32016-05-29 02:01:14 +0000342 MAI->setRelaxELFRelocations(Opts.RelaxELFRelocations);
343
Daniel Dunbar2fcaa542010-05-20 17:49:16 +0000344 bool IsBinary = Opts.OutputType == AssemblerInvocation::FT_Obj;
Amara Emersonf528bcc2018-05-22 11:18:58 +0000345 std::unique_ptr<raw_fd_ostream> FDOS = getOutputStream(Opts, Diags, IsBinary);
Rafael Espindola2f16bc12015-04-14 15:15:49 +0000346 if (!FDOS)
Alp Toker44293142014-05-31 00:02:27 +0000347 return true;
Daniel Dunbar2fcaa542010-05-20 17:49:16 +0000348
Evan Cheng347033f2011-07-20 06:22:27 +0000349 // FIXME: This is not pretty. MCContext has a ptr to MCObjectFileInfo and
350 // MCObjectFileInfo needs a MCContext reference in order to initialize itself.
Ahmed Charlesb8984322014-03-07 20:03:18 +0000351 std::unique_ptr<MCObjectFileInfo> MOFI(new MCObjectFileInfo());
David Blaikie07b8d4e2014-03-31 23:13:30 +0000352
Bill Wendlingda1e3e72013-06-18 07:22:05 +0000353 MCContext Ctx(MAI.get(), MRI.get(), MOFI.get(), &SrcMgr);
Joerg Sonnenberger924f6ad2015-09-18 11:13:43 +0000354
Rafael Espindolae64e2302016-05-18 11:58:56 +0000355 bool PIC = false;
Joerg Sonnenberger924f6ad2015-09-18 11:13:43 +0000356 if (Opts.RelocationModel == "static") {
Rafael Espindolae64e2302016-05-18 11:58:56 +0000357 PIC = false;
Joerg Sonnenberger924f6ad2015-09-18 11:13:43 +0000358 } else if (Opts.RelocationModel == "pic") {
Rafael Espindolae64e2302016-05-18 11:58:56 +0000359 PIC = true;
Joerg Sonnenberger924f6ad2015-09-18 11:13:43 +0000360 } else {
361 assert(Opts.RelocationModel == "dynamic-no-pic" &&
362 "Invalid PIC model!");
Rafael Espindolae64e2302016-05-18 11:58:56 +0000363 PIC = false;
Joerg Sonnenberger924f6ad2015-09-18 11:13:43 +0000364 }
365
Rafael Espindola2e8a7d32017-08-02 20:32:35 +0000366 MOFI->InitMCObjectFileInfo(Triple(Opts.Triple), PIC, Ctx);
Daniel Dunbar9cf7bc72011-03-28 22:49:24 +0000367 if (Opts.SaveTemporaryLabels)
368 Ctx.setAllowTemporaryLabels(false);
Kevin Enderby292dc082011-12-22 19:31:58 +0000369 if (Opts.GenDwarfForAssembly)
370 Ctx.setGenDwarfForAssembly(true);
371 if (!Opts.DwarfDebugFlags.empty())
372 Ctx.setDwarfDebugFlags(StringRef(Opts.DwarfDebugFlags));
Kevin Enderbyae2ec472013-01-17 21:38:06 +0000373 if (!Opts.DwarfDebugProducer.empty())
374 Ctx.setDwarfDebugProducer(StringRef(Opts.DwarfDebugProducer));
Chandler Carruth4d5e1a92012-12-17 21:40:04 +0000375 if (!Opts.DebugCompilationDir.empty())
376 Ctx.setCompilationDir(Opts.DebugCompilationDir);
Eric Christopher45f2e712012-12-18 00:31:10 +0000377 if (!Opts.MainFileName.empty())
378 Ctx.setMainFileName(StringRef(Opts.MainFileName));
Oliver Stannard9b2a7d42014-05-19 13:39:13 +0000379 Ctx.setDwarfVersion(Opts.DwarfVersion);
Rafael Espindola86f2c572010-12-10 07:40:14 +0000380
Jim Grosbach576452b2012-02-10 20:37:10 +0000381 // Build up the feature string from the target feature list.
382 std::string FS;
383 if (!Opts.Features.empty()) {
384 FS = Opts.Features[0];
385 for (unsigned i = 1, e = Opts.Features.size(); i != e; ++i)
386 FS += "," + Opts.Features[i];
387 }
388
Ahmed Charlesb8984322014-03-07 20:03:18 +0000389 std::unique_ptr<MCStreamer> Str;
Daniel Dunbar2fcaa542010-05-20 17:49:16 +0000390
Ahmed Charlesb8984322014-03-07 20:03:18 +0000391 std::unique_ptr<MCInstrInfo> MCII(TheTarget->createMCInstrInfo());
392 std::unique_ptr<MCSubtargetInfo> STI(
393 TheTarget->createMCSubtargetInfo(Opts.Triple, Opts.CPU, FS));
Evan Cheng279f2902011-07-11 04:24:19 +0000394
Rafael Espindola2f16bc12015-04-14 15:15:49 +0000395 raw_pwrite_stream *Out = FDOS.get();
396 std::unique_ptr<buffer_ostream> BOS;
397
Rafael Espindola148141c2011-01-23 17:58:26 +0000398 // FIXME: There is a bit of code duplication with addPassesToEmitFile.
Daniel Dunbar2fcaa542010-05-20 17:49:16 +0000399 if (Opts.OutputType == AssemblerInvocation::FT_Asm) {
Eric Christopher7e0fadf2015-03-31 00:10:23 +0000400 MCInstPrinter *IP = TheTarget->createMCInstPrinter(
Daniel Sanders50f17232015-09-15 16:17:27 +0000401 llvm::Triple(Opts.Triple), Opts.OutputAsmVariant, *MAI, *MCII, *MRI);
Nirav Dave1b5533c2018-04-27 15:45:54 +0000402
403 std::unique_ptr<MCCodeEmitter> CE;
404 if (Opts.ShowEncoding)
405 CE.reset(TheTarget->createMCCodeEmitter(*MCII, *MRI, Ctx));
406 MCTargetOptions MCOptions;
407 std::unique_ptr<MCAsmBackend> MAB(
408 TheTarget->createMCAsmBackend(*STI, *MRI, MCOptions));
409
Rafael Espindola4dedcd72015-04-09 21:06:11 +0000410 auto FOut = llvm::make_unique<formatted_raw_ostream>(*Out);
411 Str.reset(TheTarget->createAsmStreamer(
412 Ctx, std::move(FOut), /*asmverbose*/ true,
Nirav Dave1b5533c2018-04-27 15:45:54 +0000413 /*useDwarfDirectory*/ true, IP, std::move(CE), std::move(MAB),
414 Opts.ShowInst));
Daniel Dunbar2fcaa542010-05-20 17:49:16 +0000415 } else if (Opts.OutputType == AssemblerInvocation::FT_Null) {
416 Str.reset(createNullStreamer(Ctx));
417 } else {
418 assert(Opts.OutputType == AssemblerInvocation::FT_Obj &&
419 "Invalid file type!");
Rafael Espindola2f16bc12015-04-14 15:15:49 +0000420 if (!FDOS->supportsSeeking()) {
421 BOS = make_unique<buffer_ostream>(*FDOS);
422 Out = BOS.get();
423 }
424
Nirav Dave1b5533c2018-04-27 15:45:54 +0000425 std::unique_ptr<MCCodeEmitter> CE(
426 TheTarget->createMCCodeEmitter(*MCII, *MRI, Ctx));
427 MCTargetOptions MCOptions;
428 std::unique_ptr<MCAsmBackend> MAB(
429 TheTarget->createMCAsmBackend(*STI, *MRI, MCOptions));
Amara Emersonf528bcc2018-05-22 11:18:58 +0000430 std::unique_ptr<MCObjectWriter> OW = MAB->createObjectWriter(*Out);
Nirav Dave1b5533c2018-04-27 15:45:54 +0000431
Daniel Sanders50f17232015-09-15 16:17:27 +0000432 Triple T(Opts.Triple);
David Majnemer2b9349d2015-12-21 22:09:34 +0000433 Str.reset(TheTarget->createMCObjectStreamer(
Peter Collingbournef7b81db2018-05-18 18:26:45 +0000434 T, Ctx, std::move(MAB), std::move(OW), std::move(CE), *STI,
435 Opts.RelaxAll, Opts.IncrementalLinkerCompatible,
David Majnemer2b9349d2015-12-21 22:09:34 +0000436 /*DWARFMustBeAtTheEnd*/ true));
Rafael Espindolad465be82014-10-15 16:12:57 +0000437 Str.get()->InitSections(Opts.NoExecStack);
Daniel Dunbar2fcaa542010-05-20 17:49:16 +0000438 }
439
Nirav Dave6c0665e2018-04-30 19:22:40 +0000440 // Assembly to object compilation should leverage assembly info.
441 Str->setUseAssemblerInfoForParsing(true);
442
Alp Toker44293142014-05-31 00:02:27 +0000443 bool Failed = false;
Alp Tokere98ea7c2014-05-31 00:02:21 +0000444
Ahmed Charlesb8984322014-03-07 20:03:18 +0000445 std::unique_ptr<MCAsmParser> Parser(
446 createMCAsmParser(SrcMgr, Ctx, *Str.get(), *MAI));
Evgeniy Stepanoveeb820f2014-04-23 11:15:49 +0000447
448 // FIXME: init MCTargetOptions from sanitizer flags here.
449 MCTargetOptions Options;
Ahmed Charlesb8984322014-03-07 20:03:18 +0000450 std::unique_ptr<MCTargetAsmParser> TAP(
Evgeniy Stepanoveeb820f2014-04-23 11:15:49 +0000451 TheTarget->createMCAsmParser(*STI, *Parser, *MCII, Options));
Alp Toker44293142014-05-31 00:02:27 +0000452 if (!TAP)
453 Failed = Diags.Report(diag::err_target_unknown_triple) << Opts.Triple;
Daniel Dunbar2fcaa542010-05-20 17:49:16 +0000454
Mandeep Singh Grang358faec2016-12-01 18:42:16 +0000455 // Set values for symbols, if any.
456 for (auto &S : Opts.SymbolDefs) {
Mandeep Singh Grang6d1d36c2016-12-06 02:49:16 +0000457 auto Pair = StringRef(S).split('=');
458 auto Sym = Pair.first;
459 auto Val = Pair.second;
460 int64_t Value;
461 // We have already error checked this in the driver.
462 Val.getAsInteger(0, Value);
463 Ctx.setSymbolValue(Parser->getStreamer(), Sym, Value);
Mandeep Singh Grang358faec2016-12-01 18:42:16 +0000464 }
465
Alp Toker44293142014-05-31 00:02:27 +0000466 if (!Failed) {
Alp Tokere98ea7c2014-05-31 00:02:21 +0000467 Parser->setTargetParser(*TAP.get());
Alp Toker44293142014-05-31 00:02:27 +0000468 Failed = Parser->Run(Opts.NoInitialTextSection);
Alp Tokere98ea7c2014-05-31 00:02:21 +0000469 }
Daniel Dunbar2fcaa542010-05-20 17:49:16 +0000470
Steven Wuae480ec2015-07-24 02:12:43 +0000471 // Close Streamer first.
472 // It might have a reference to the output stream.
473 Str.reset();
Alp Tokere98ea7c2014-05-31 00:02:21 +0000474 // Close the output stream early.
Rafael Espindola2f16bc12015-04-14 15:15:49 +0000475 BOS.reset();
476 FDOS.reset();
Daniel Dunbar2fcaa542010-05-20 17:49:16 +0000477
Alp Tokere98ea7c2014-05-31 00:02:21 +0000478 // Delete output file if there were errors.
Amara Emersonf528bcc2018-05-22 11:18:58 +0000479 if (Failed && Opts.OutputPath != "-")
480 sys::fs::remove(Opts.OutputPath);
Daniel Dunbar2fcaa542010-05-20 17:49:16 +0000481
Alp Toker44293142014-05-31 00:02:27 +0000482 return Failed;
Daniel Dunbar2fcaa542010-05-20 17:49:16 +0000483}
484
Chad Rosier05c71aa2013-03-27 18:28:23 +0000485static void LLVMErrorHandler(void *UserData, const std::string &Message,
486 bool GenCrashDiag) {
David Blaikie9c902b52011-09-25 23:23:43 +0000487 DiagnosticsEngine &Diags = *static_cast<DiagnosticsEngine*>(UserData);
Daniel Dunbar2fcaa542010-05-20 17:49:16 +0000488
489 Diags.Report(diag::err_fe_error_backend) << Message;
490
491 // We cannot recover from llvm errors.
492 exit(1);
493}
494
Sean Silva070cd2d2014-08-15 21:38:36 +0000495int cc1as_main(ArrayRef<const char *> Argv, const char *Argv0, void *MainAddr) {
Daniel Dunbar2fcaa542010-05-20 17:49:16 +0000496 // Initialize targets and assembly printers/parsers.
497 InitializeAllTargetInfos();
Evan Chengc391a582011-07-22 21:59:11 +0000498 InitializeAllTargetMCs();
Daniel Dunbar2fcaa542010-05-20 17:49:16 +0000499 InitializeAllAsmParsers();
500
501 // Construct our diagnostic client.
Douglas Gregor811db4e2012-10-23 22:26:28 +0000502 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts = new DiagnosticOptions();
Douglas Gregor2dd19f12010-08-18 22:29:43 +0000503 TextDiagnosticPrinter *DiagClient
Douglas Gregor811db4e2012-10-23 22:26:28 +0000504 = new TextDiagnosticPrinter(errs(), &*DiagOpts);
Douglas Gregor2dd19f12010-08-18 22:29:43 +0000505 DiagClient->setPrefix("clang -cc1as");
Dylan Noblesmithc95d8192012-02-20 14:00:23 +0000506 IntrusiveRefCntPtr<DiagnosticIDs> DiagID(new DiagnosticIDs());
Douglas Gregor811db4e2012-10-23 22:26:28 +0000507 DiagnosticsEngine Diags(DiagID, &*DiagOpts, DiagClient);
Daniel Dunbar2fcaa542010-05-20 17:49:16 +0000508
509 // Set an error handler, so that any LLVM backend diagnostics go through our
510 // error handler.
Dan Gohmanb37af7d2010-08-18 21:23:17 +0000511 ScopedFatalErrorHandler FatalErrorHandler
512 (LLVMErrorHandler, static_cast<void*>(&Diags));
Daniel Dunbar2fcaa542010-05-20 17:49:16 +0000513
514 // Parse the arguments.
515 AssemblerInvocation Asm;
Sean Silva070cd2d2014-08-15 21:38:36 +0000516 if (!AssemblerInvocation::CreateFromArgs(Asm, Argv, Diags))
Dylan Noblesmithe99b27f2011-12-23 03:05:38 +0000517 return 1;
Daniel Dunbar2fcaa542010-05-20 17:49:16 +0000518
Daniel Dunbar0454f652010-05-20 18:15:20 +0000519 if (Asm.ShowHelp) {
Alp Toker61dad752014-07-09 14:05:11 +0000520 std::unique_ptr<OptTable> Opts(driver::createDriverOptTable());
Alp Toker532e5b92014-07-09 14:09:52 +0000521 Opts->PrintHelp(llvm::outs(), "clang -cc1as", "Clang Integrated Assembler",
George Rimar5dbfa4e2017-07-26 09:10:17 +0000522 /*Include=*/driver::options::CC1AsOption, /*Exclude=*/0,
523 /*ShowAllAliases=*/false);
Daniel Dunbar0454f652010-05-20 18:15:20 +0000524 return 0;
525 }
526
527 // Honor -version.
528 //
529 // FIXME: Use a better -version message?
530 if (Asm.ShowVersion) {
531 llvm::cl::PrintVersionMessage();
532 return 0;
533 }
534
535 // Honor -mllvm.
536 //
537 // FIXME: Remove this, one day.
538 if (!Asm.LLVMArgs.empty()) {
539 unsigned NumArgs = Asm.LLVMArgs.size();
Kostya Serebryany5af45152017-04-19 20:57:13 +0000540 auto Args = llvm::make_unique<const char*[]>(NumArgs + 2);
Daniel Dunbar0454f652010-05-20 18:15:20 +0000541 Args[0] = "clang (LLVM option parsing)";
542 for (unsigned i = 0; i != NumArgs; ++i)
543 Args[i + 1] = Asm.LLVMArgs[i].c_str();
Craig Topper69186e72014-06-08 08:38:04 +0000544 Args[NumArgs + 1] = nullptr;
Kostya Serebryany5af45152017-04-19 20:57:13 +0000545 llvm::cl::ParseCommandLineOptions(NumArgs + 1, Args.get());
Daniel Dunbar0454f652010-05-20 18:15:20 +0000546 }
547
Daniel Dunbar2fcaa542010-05-20 17:49:16 +0000548 // Execute the invocation, unless there were parsing errors.
Alp Toker44293142014-05-31 00:02:27 +0000549 bool Failed = Diags.hasErrorOccurred() || ExecuteAssembler(Asm, Diags);
Daniel Dunbar2fcaa542010-05-20 17:49:16 +0000550
551 // If any timers were active but haven't been destroyed yet, print their
552 // results now.
553 TimerGroup::printAll(errs());
554
Alp Toker44293142014-05-31 00:02:27 +0000555 return !!Failed;
Daniel Dunbar2fcaa542010-05-20 17:49:16 +0000556}