blob: c9361541cdf4d64d4a3c09b18488d0fcb45a3112 [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"
Chandler Carruthcc0694c2012-12-04 09:25:21 +000032#include "llvm/MC/MCParser/MCAsmParser.h"
Benjamin Kramer5e456302016-01-27 10:01:30 +000033#include "llvm/MC/MCParser/MCTargetAsmParser.h"
Evan Chengb505ace2011-07-18 20:57:51 +000034#include "llvm/MC/MCRegisterInfo.h"
Daniel Dunbar2fcaa542010-05-20 17:49:16 +000035#include "llvm/MC/MCStreamer.h"
Evan Chengdec31872011-07-09 06:04:17 +000036#include "llvm/MC/MCSubtargetInfo.h"
Evgeniy Stepanoveeb820f2014-04-23 11:15:49 +000037#include "llvm/MC/MCTargetOptions.h"
Reid Kleckner898229a2013-06-14 17:17:23 +000038#include "llvm/Option/Arg.h"
39#include "llvm/Option/ArgList.h"
40#include "llvm/Option/OptTable.h"
Daniel Dunbar0454f652010-05-20 18:15:20 +000041#include "llvm/Support/CommandLine.h"
Daniel Dunbar2fcaa542010-05-20 17:49:16 +000042#include "llvm/Support/ErrorHandling.h"
Rafael Espindolaccc6ea62013-06-26 12:48:34 +000043#include "llvm/Support/FileSystem.h"
Chandler Carruthcc0694c2012-12-04 09:25:21 +000044#include "llvm/Support/FormattedStream.h"
45#include "llvm/Support/Host.h"
Daniel Dunbar2fcaa542010-05-20 17:49:16 +000046#include "llvm/Support/MemoryBuffer.h"
Michael J. Spencer8aaf4992010-11-29 18:12:39 +000047#include "llvm/Support/Path.h"
48#include "llvm/Support/Signals.h"
Chandler Carruthcc0694c2012-12-04 09:25:21 +000049#include "llvm/Support/SourceMgr.h"
Evan Cheng494eb062011-08-24 18:09:14 +000050#include "llvm/Support/TargetRegistry.h"
51#include "llvm/Support/TargetSelect.h"
52#include "llvm/Support/Timer.h"
53#include "llvm/Support/raw_ostream.h"
Ahmed Charlesdfca6f92014-03-09 11:36:40 +000054#include <memory>
Rafael Espindola8a8e5542014-06-12 17:19:42 +000055#include <system_error>
Daniel Dunbar2fcaa542010-05-20 17:49:16 +000056using namespace clang;
57using namespace clang::driver;
Alp Toker61dad752014-07-09 14:05:11 +000058using namespace clang::driver::options;
Daniel Dunbar2fcaa542010-05-20 17:49:16 +000059using namespace llvm;
Reid Kleckner898229a2013-06-14 17:17:23 +000060using namespace llvm::opt;
Daniel Dunbar2fcaa542010-05-20 17:49:16 +000061
62namespace {
63
64/// \brief Helper class for representing a single invocation of the assembler.
65struct AssemblerInvocation {
66 /// @name Target Options
67 /// @{
68
Jim Grosbach576452b2012-02-10 20:37:10 +000069 /// The name of the target triple to assemble for.
Daniel Dunbar2fcaa542010-05-20 17:49:16 +000070 std::string Triple;
71
Jim Grosbach576452b2012-02-10 20:37:10 +000072 /// If given, the name of the target CPU to determine which instructions
73 /// are legal.
74 std::string CPU;
75
76 /// The list of target specific features to enable or disable -- this should
77 /// be a list of strings starting with '+' or '-'.
78 std::vector<std::string> Features;
79
Mandeep Singh Grang358faec2016-12-01 18:42:16 +000080 /// The list of symbol definitions.
81 std::vector<std::string> SymbolDefs;
82
Daniel Dunbar2fcaa542010-05-20 17:49:16 +000083 /// @}
84 /// @name Language Options
85 /// @{
86
87 std::vector<std::string> IncludePaths;
88 unsigned NoInitialTextSection : 1;
Daniel Dunbar9cf7bc72011-03-28 22:49:24 +000089 unsigned SaveTemporaryLabels : 1;
Kevin Enderby292dc082011-12-22 19:31:58 +000090 unsigned GenDwarfForAssembly : 1;
David Blaikie7e2fd942014-03-27 20:47:30 +000091 unsigned CompressDebugSections : 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;
Eric Christopher45f2e712012-12-18 00:31:10 +000097 std::string MainFileName;
Daniel Dunbar2fcaa542010-05-20 17:49:16 +000098
99 /// @}
100 /// @name Frontend Options
101 /// @{
102
103 std::string InputFile;
Daniel Dunbar0454f652010-05-20 18:15:20 +0000104 std::vector<std::string> LLVMArgs;
Daniel Dunbar2fcaa542010-05-20 17:49:16 +0000105 std::string OutputPath;
106 enum FileType {
107 FT_Asm, ///< Assembly (.s) output, transliterate mode.
108 FT_Null, ///< No output, for timing purposes.
109 FT_Obj ///< Object file output.
110 };
111 FileType OutputType;
Daniel Dunbar0454f652010-05-20 18:15:20 +0000112 unsigned ShowHelp : 1;
113 unsigned ShowVersion : 1;
Daniel Dunbar2fcaa542010-05-20 17:49:16 +0000114
115 /// @}
116 /// @name Transliterate Options
117 /// @{
118
119 unsigned OutputAsmVariant;
120 unsigned ShowEncoding : 1;
121 unsigned ShowInst : 1;
122
123 /// @}
124 /// @name Assembler Options
125 /// @{
126
127 unsigned RelaxAll : 1;
Rafael Espindola148141c2011-01-23 17:58:26 +0000128 unsigned NoExecStack : 1;
Joerg Sonnenbergera43604a2014-08-26 18:40:25 +0000129 unsigned FatalWarnings : 1;
David Majnemer2b9349d2015-12-21 22:09:34 +0000130 unsigned IncrementalLinkerCompatible : 1;
Daniel Dunbar2fcaa542010-05-20 17:49:16 +0000131
Joerg Sonnenberger924f6ad2015-09-18 11:13:43 +0000132 /// The name of the relocation model to use.
133 std::string RelocationModel;
134
Daniel Dunbar2fcaa542010-05-20 17:49:16 +0000135 /// @}
136
137public:
138 AssemblerInvocation() {
139 Triple = "";
140 NoInitialTextSection = 0;
141 InputFile = "-";
Daniel Dunbar0454f652010-05-20 18:15:20 +0000142 OutputPath = "-";
Daniel Dunbar2fcaa542010-05-20 17:49:16 +0000143 OutputType = FT_Asm;
144 OutputAsmVariant = 0;
145 ShowInst = 0;
146 ShowEncoding = 0;
147 RelaxAll = 0;
Rafael Espindola148141c2011-01-23 17:58:26 +0000148 NoExecStack = 0;
Joerg Sonnenbergera43604a2014-08-26 18:40:25 +0000149 FatalWarnings = 0;
David Majnemer2b9349d2015-12-21 22:09:34 +0000150 IncrementalLinkerCompatible = 0;
Douglas Katzman722bcb02015-10-13 16:22:51 +0000151 DwarfVersion = 0;
Daniel Dunbar2fcaa542010-05-20 17:49:16 +0000152 }
153
Sean Silva070cd2d2014-08-15 21:38:36 +0000154 static bool CreateFromArgs(AssemblerInvocation &Res,
155 ArrayRef<const char *> Argv,
156 DiagnosticsEngine &Diags);
Daniel Dunbar2fcaa542010-05-20 17:49:16 +0000157};
158
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000159}
Daniel Dunbar2fcaa542010-05-20 17:49:16 +0000160
Dylan Noblesmithe99b27f2011-12-23 03:05:38 +0000161bool AssemblerInvocation::CreateFromArgs(AssemblerInvocation &Opts,
Sean Silva070cd2d2014-08-15 21:38:36 +0000162 ArrayRef<const char *> Argv,
David Blaikie9c902b52011-09-25 23:23:43 +0000163 DiagnosticsEngine &Diags) {
Dylan Noblesmithe99b27f2011-12-23 03:05:38 +0000164 bool Success = true;
165
Daniel Dunbar2fcaa542010-05-20 17:49:16 +0000166 // Parse the arguments.
Alp Toker61dad752014-07-09 14:05:11 +0000167 std::unique_ptr<OptTable> OptTbl(createDriverOptTable());
168
169 const unsigned IncludedFlagsBitmask = options::CC1AsOption;
Daniel Dunbar2fcaa542010-05-20 17:49:16 +0000170 unsigned MissingArgIndex, MissingArgCount;
David Blaikie69a1d8c2015-06-22 22:07:27 +0000171 InputArgList Args = OptTbl->ParseArgs(Argv, MissingArgIndex, MissingArgCount,
172 IncludedFlagsBitmask);
Daniel Dunbar2fcaa542010-05-20 17:49:16 +0000173
174 // Check for missing argument error.
Dylan Noblesmithe99b27f2011-12-23 03:05:38 +0000175 if (MissingArgCount) {
Daniel Dunbar2fcaa542010-05-20 17:49:16 +0000176 Diags.Report(diag::err_drv_missing_argument)
David Blaikie69a1d8c2015-06-22 22:07:27 +0000177 << Args.getArgString(MissingArgIndex) << MissingArgCount;
Dylan Noblesmithe99b27f2011-12-23 03:05:38 +0000178 Success = false;
179 }
Daniel Dunbar2fcaa542010-05-20 17:49:16 +0000180
181 // Issue errors on unknown arguments.
David Blaikie69a1d8c2015-06-22 22:07:27 +0000182 for (const Arg *A : Args.filtered(OPT_UNKNOWN)) {
183 Diags.Report(diag::err_drv_unknown_argument) << A->getAsString(Args);
Dylan Noblesmithe99b27f2011-12-23 03:05:38 +0000184 Success = false;
185 }
Daniel Dunbar2fcaa542010-05-20 17:49:16 +0000186
187 // Construct the invocation.
188
189 // Target Options
David Blaikie69a1d8c2015-06-22 22:07:27 +0000190 Opts.Triple = llvm::Triple::normalize(Args.getLastArgValue(OPT_triple));
191 Opts.CPU = Args.getLastArgValue(OPT_target_cpu);
192 Opts.Features = Args.getAllArgValues(OPT_target_feature);
Jim Grosbach576452b2012-02-10 20:37:10 +0000193
194 // Use the default target triple if unspecified.
195 if (Opts.Triple.empty())
196 Opts.Triple = llvm::sys::getDefaultTargetTriple();
Daniel Dunbar2fcaa542010-05-20 17:49:16 +0000197
198 // Language Options
David Blaikie69a1d8c2015-06-22 22:07:27 +0000199 Opts.IncludePaths = Args.getAllArgValues(OPT_I);
200 Opts.NoInitialTextSection = Args.hasArg(OPT_n);
201 Opts.SaveTemporaryLabels = Args.hasArg(OPT_msave_temp_labels);
Douglas Katzman3459ce22015-10-08 04:24:12 +0000202 // Any DebugInfoKind implies GenDwarfForAssembly.
203 Opts.GenDwarfForAssembly = Args.hasArg(OPT_debug_info_kind_EQ);
David Blaikie69a1d8c2015-06-22 22:07:27 +0000204 Opts.CompressDebugSections = Args.hasArg(OPT_compress_debug_sections);
Rafael Espindolaf8f01c32016-05-29 02:01:14 +0000205 Opts.RelaxELFRelocations = Args.hasArg(OPT_mrelax_relocations);
Adrian Prantlae39ccc2016-04-19 20:31:19 +0000206 Opts.DwarfVersion = getLastArgIntValue(Args, OPT_dwarf_version_EQ, 2, Diags);
David Blaikie69a1d8c2015-06-22 22:07:27 +0000207 Opts.DwarfDebugFlags = Args.getLastArgValue(OPT_dwarf_debug_flags);
208 Opts.DwarfDebugProducer = Args.getLastArgValue(OPT_dwarf_debug_producer);
209 Opts.DebugCompilationDir = Args.getLastArgValue(OPT_fdebug_compilation_dir);
210 Opts.MainFileName = Args.getLastArgValue(OPT_main_file_name);
Daniel Dunbar2fcaa542010-05-20 17:49:16 +0000211
212 // Frontend Options
David Blaikie69a1d8c2015-06-22 22:07:27 +0000213 if (Args.hasArg(OPT_INPUT)) {
Daniel Dunbar2fcaa542010-05-20 17:49:16 +0000214 bool First = true;
David Blaikie69a1d8c2015-06-22 22:07:27 +0000215 for (arg_iterator it = Args.filtered_begin(OPT_INPUT),
216 ie = Args.filtered_end();
217 it != ie; ++it, First = false) {
Daniel Dunbara442fd52010-06-11 22:00:13 +0000218 const Arg *A = it;
Daniel Dunbar2fcaa542010-05-20 17:49:16 +0000219 if (First)
Richard Smithbd55daf2012-11-01 04:30:05 +0000220 Opts.InputFile = A->getValue();
Dylan Noblesmithe99b27f2011-12-23 03:05:38 +0000221 else {
David Blaikie69a1d8c2015-06-22 22:07:27 +0000222 Diags.Report(diag::err_drv_unknown_argument) << A->getAsString(Args);
Dylan Noblesmithe99b27f2011-12-23 03:05:38 +0000223 Success = false;
224 }
Daniel Dunbar2fcaa542010-05-20 17:49:16 +0000225 }
226 }
David Blaikie69a1d8c2015-06-22 22:07:27 +0000227 Opts.LLVMArgs = Args.getAllArgValues(OPT_mllvm);
228 Opts.OutputPath = Args.getLastArgValue(OPT_o);
229 if (Arg *A = Args.getLastArg(OPT_filetype)) {
Richard Smithbd55daf2012-11-01 04:30:05 +0000230 StringRef Name = A->getValue();
Daniel Dunbar2fcaa542010-05-20 17:49:16 +0000231 unsigned OutputType = StringSwitch<unsigned>(Name)
232 .Case("asm", FT_Asm)
233 .Case("null", FT_Null)
234 .Case("obj", FT_Obj)
235 .Default(~0U);
Dylan Noblesmithe99b27f2011-12-23 03:05:38 +0000236 if (OutputType == ~0U) {
David Blaikie69a1d8c2015-06-22 22:07:27 +0000237 Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << Name;
Dylan Noblesmithe99b27f2011-12-23 03:05:38 +0000238 Success = false;
239 } else
Daniel Dunbar2fcaa542010-05-20 17:49:16 +0000240 Opts.OutputType = FileType(OutputType);
241 }
David Blaikie69a1d8c2015-06-22 22:07:27 +0000242 Opts.ShowHelp = Args.hasArg(OPT_help);
243 Opts.ShowVersion = Args.hasArg(OPT_version);
Daniel Dunbar2fcaa542010-05-20 17:49:16 +0000244
245 // Transliterate Options
Reid Kleckner898229a2013-06-14 17:17:23 +0000246 Opts.OutputAsmVariant =
David Blaikie69a1d8c2015-06-22 22:07:27 +0000247 getLastArgIntValue(Args, OPT_output_asm_variant, 0, Diags);
248 Opts.ShowEncoding = Args.hasArg(OPT_show_encoding);
249 Opts.ShowInst = Args.hasArg(OPT_show_inst);
Daniel Dunbar2fcaa542010-05-20 17:49:16 +0000250
251 // Assemble Options
David Blaikie69a1d8c2015-06-22 22:07:27 +0000252 Opts.RelaxAll = Args.hasArg(OPT_mrelax_all);
253 Opts.NoExecStack = Args.hasArg(OPT_mno_exec_stack);
254 Opts.FatalWarnings = Args.hasArg(OPT_massembler_fatal_warnings);
Joerg Sonnenberger924f6ad2015-09-18 11:13:43 +0000255 Opts.RelocationModel = Args.getLastArgValue(OPT_mrelocation_model, "pic");
David Majnemer2b9349d2015-12-21 22:09:34 +0000256 Opts.IncrementalLinkerCompatible =
257 Args.hasArg(OPT_mincremental_linker_compatible);
Mandeep Singh Grang358faec2016-12-01 18:42:16 +0000258 Opts.SymbolDefs = Args.getAllArgValues(OPT_defsym);
Dylan Noblesmithe99b27f2011-12-23 03:05:38 +0000259
Dylan Noblesmith68207c02011-12-26 19:29:47 +0000260 return Success;
Daniel Dunbar2fcaa542010-05-20 17:49:16 +0000261}
262
Rafael Espindola7e556ad2015-04-09 21:50:11 +0000263static std::unique_ptr<raw_fd_ostream>
264getOutputStream(AssemblerInvocation &Opts, DiagnosticsEngine &Diags,
265 bool Binary) {
Daniel Dunbar0454f652010-05-20 18:15:20 +0000266 if (Opts.OutputPath.empty())
267 Opts.OutputPath = "-";
268
Daniel Dunbar2fcaa542010-05-20 17:49:16 +0000269 // Make sure that the Out file gets unlinked from the disk if we get a
270 // SIGINT.
271 if (Opts.OutputPath != "-")
Rafael Espindola18556de2013-06-13 21:02:40 +0000272 sys::RemoveFileOnSignal(Opts.OutputPath);
Daniel Dunbar2fcaa542010-05-20 17:49:16 +0000273
Rafael Espindoladae941a2014-08-25 18:17:04 +0000274 std::error_code EC;
Rafael Espindola7e556ad2015-04-09 21:50:11 +0000275 auto Out = llvm::make_unique<raw_fd_ostream>(
Rafael Espindoladae941a2014-08-25 18:17:04 +0000276 Opts.OutputPath, EC, (Binary ? sys::fs::F_None : sys::fs::F_Text));
277 if (EC) {
278 Diags.Report(diag::err_fe_unable_to_open_output) << Opts.OutputPath
279 << EC.message();
Craig Topper69186e72014-06-08 08:38:04 +0000280 return nullptr;
Daniel Dunbar2fcaa542010-05-20 17:49:16 +0000281 }
282
Rafael Espindola4dedcd72015-04-09 21:06:11 +0000283 return Out;
Daniel Dunbar2fcaa542010-05-20 17:49:16 +0000284}
285
David Blaikie9c902b52011-09-25 23:23:43 +0000286static bool ExecuteAssembler(AssemblerInvocation &Opts,
287 DiagnosticsEngine &Diags) {
Daniel Dunbar2fcaa542010-05-20 17:49:16 +0000288 // Get the target specific parser.
289 std::string Error;
Alp Tokere98ea7c2014-05-31 00:02:21 +0000290 const Target *TheTarget = TargetRegistry::lookupTarget(Opts.Triple, Error);
Alp Toker44293142014-05-31 00:02:27 +0000291 if (!TheTarget)
292 return Diags.Report(diag::err_target_unknown_triple) << Opts.Triple;
Daniel Dunbar2fcaa542010-05-20 17:49:16 +0000293
Rafael Espindola2d2b4202014-07-06 17:43:24 +0000294 ErrorOr<std::unique_ptr<MemoryBuffer>> Buffer =
295 MemoryBuffer::getFileOrSTDIN(Opts.InputFile);
296
297 if (std::error_code EC = Buffer.getError()) {
298 Error = EC.message();
Alp Toker44293142014-05-31 00:02:27 +0000299 return Diags.Report(diag::err_fe_error_reading) << Opts.InputFile;
Daniel Dunbar2fcaa542010-05-20 17:49:16 +0000300 }
301
302 SourceMgr SrcMgr;
303
304 // Tell SrcMgr about this buffer, which is what the parser will pick up.
David Blaikie9e095d92014-08-21 21:01:00 +0000305 SrcMgr.AddNewSourceBuffer(std::move(*Buffer), SMLoc());
Daniel Dunbar2fcaa542010-05-20 17:49:16 +0000306
307 // Record the location of the include directories so that the lexer can find
308 // it later.
309 SrcMgr.setIncludeDirs(Opts.IncludePaths);
310
Ahmed Charlesb8984322014-03-07 20:03:18 +0000311 std::unique_ptr<MCRegisterInfo> MRI(TheTarget->createMCRegInfo(Opts.Triple));
Evan Chengb505ace2011-07-18 20:57:51 +0000312 assert(MRI && "Unable to create target register info!");
313
Ahmed Charlesb8984322014-03-07 20:03:18 +0000314 std::unique_ptr<MCAsmInfo> MAI(TheTarget->createMCAsmInfo(*MRI, Opts.Triple));
Rafael Espindola77056232013-05-13 01:24:18 +0000315 assert(MAI && "Unable to create target asm info!");
316
David Blaikieb31e1d12014-03-31 23:47:13 +0000317 // Ensure MCAsmInfo initialization occurs before any use, otherwise sections
318 // may be created with a combination of default and explicit settings.
319 if (Opts.CompressDebugSections)
George Rimar0976dc12016-05-27 12:15:25 +0000320 MAI->setCompressDebugSections(DebugCompressionType::DCT_ZlibGnu);
David Blaikieb31e1d12014-03-31 23:47:13 +0000321
Rafael Espindolaf8f01c32016-05-29 02:01:14 +0000322 MAI->setRelaxELFRelocations(Opts.RelaxELFRelocations);
323
Daniel Dunbar2fcaa542010-05-20 17:49:16 +0000324 bool IsBinary = Opts.OutputType == AssemblerInvocation::FT_Obj;
Rafael Espindola2f16bc12015-04-14 15:15:49 +0000325 std::unique_ptr<raw_fd_ostream> FDOS = getOutputStream(Opts, Diags, IsBinary);
326 if (!FDOS)
Alp Toker44293142014-05-31 00:02:27 +0000327 return true;
Daniel Dunbar2fcaa542010-05-20 17:49:16 +0000328
Evan Cheng347033f2011-07-20 06:22:27 +0000329 // FIXME: This is not pretty. MCContext has a ptr to MCObjectFileInfo and
330 // MCObjectFileInfo needs a MCContext reference in order to initialize itself.
Ahmed Charlesb8984322014-03-07 20:03:18 +0000331 std::unique_ptr<MCObjectFileInfo> MOFI(new MCObjectFileInfo());
David Blaikie07b8d4e2014-03-31 23:13:30 +0000332
Bill Wendlingda1e3e72013-06-18 07:22:05 +0000333 MCContext Ctx(MAI.get(), MRI.get(), MOFI.get(), &SrcMgr);
Joerg Sonnenberger924f6ad2015-09-18 11:13:43 +0000334
Rafael Espindolae64e2302016-05-18 11:58:56 +0000335 bool PIC = false;
Joerg Sonnenberger924f6ad2015-09-18 11:13:43 +0000336 if (Opts.RelocationModel == "static") {
Rafael Espindolae64e2302016-05-18 11:58:56 +0000337 PIC = false;
Joerg Sonnenberger924f6ad2015-09-18 11:13:43 +0000338 } else if (Opts.RelocationModel == "pic") {
Rafael Espindolae64e2302016-05-18 11:58:56 +0000339 PIC = true;
Joerg Sonnenberger924f6ad2015-09-18 11:13:43 +0000340 } else {
341 assert(Opts.RelocationModel == "dynamic-no-pic" &&
342 "Invalid PIC model!");
Rafael Espindolae64e2302016-05-18 11:58:56 +0000343 PIC = false;
Joerg Sonnenberger924f6ad2015-09-18 11:13:43 +0000344 }
345
Rafael Espindolae64e2302016-05-18 11:58:56 +0000346 MOFI->InitMCObjectFileInfo(Triple(Opts.Triple), PIC, CodeModel::Default, Ctx);
Daniel Dunbar9cf7bc72011-03-28 22:49:24 +0000347 if (Opts.SaveTemporaryLabels)
348 Ctx.setAllowTemporaryLabels(false);
Kevin Enderby292dc082011-12-22 19:31:58 +0000349 if (Opts.GenDwarfForAssembly)
350 Ctx.setGenDwarfForAssembly(true);
351 if (!Opts.DwarfDebugFlags.empty())
352 Ctx.setDwarfDebugFlags(StringRef(Opts.DwarfDebugFlags));
Kevin Enderbyae2ec472013-01-17 21:38:06 +0000353 if (!Opts.DwarfDebugProducer.empty())
354 Ctx.setDwarfDebugProducer(StringRef(Opts.DwarfDebugProducer));
Chandler Carruth4d5e1a92012-12-17 21:40:04 +0000355 if (!Opts.DebugCompilationDir.empty())
356 Ctx.setCompilationDir(Opts.DebugCompilationDir);
Eric Christopher45f2e712012-12-18 00:31:10 +0000357 if (!Opts.MainFileName.empty())
358 Ctx.setMainFileName(StringRef(Opts.MainFileName));
Oliver Stannard9b2a7d42014-05-19 13:39:13 +0000359 Ctx.setDwarfVersion(Opts.DwarfVersion);
Rafael Espindola86f2c572010-12-10 07:40:14 +0000360
Jim Grosbach576452b2012-02-10 20:37:10 +0000361 // Build up the feature string from the target feature list.
362 std::string FS;
363 if (!Opts.Features.empty()) {
364 FS = Opts.Features[0];
365 for (unsigned i = 1, e = Opts.Features.size(); i != e; ++i)
366 FS += "," + Opts.Features[i];
367 }
368
Ahmed Charlesb8984322014-03-07 20:03:18 +0000369 std::unique_ptr<MCStreamer> Str;
Daniel Dunbar2fcaa542010-05-20 17:49:16 +0000370
Ahmed Charlesb8984322014-03-07 20:03:18 +0000371 std::unique_ptr<MCInstrInfo> MCII(TheTarget->createMCInstrInfo());
372 std::unique_ptr<MCSubtargetInfo> STI(
373 TheTarget->createMCSubtargetInfo(Opts.Triple, Opts.CPU, FS));
Evan Cheng279f2902011-07-11 04:24:19 +0000374
Rafael Espindola2f16bc12015-04-14 15:15:49 +0000375 raw_pwrite_stream *Out = FDOS.get();
376 std::unique_ptr<buffer_ostream> BOS;
377
Rafael Espindola148141c2011-01-23 17:58:26 +0000378 // FIXME: There is a bit of code duplication with addPassesToEmitFile.
Daniel Dunbar2fcaa542010-05-20 17:49:16 +0000379 if (Opts.OutputType == AssemblerInvocation::FT_Asm) {
Eric Christopher7e0fadf2015-03-31 00:10:23 +0000380 MCInstPrinter *IP = TheTarget->createMCInstPrinter(
Daniel Sanders50f17232015-09-15 16:17:27 +0000381 llvm::Triple(Opts.Triple), Opts.OutputAsmVariant, *MAI, *MCII, *MRI);
Craig Topper69186e72014-06-08 08:38:04 +0000382 MCCodeEmitter *CE = nullptr;
383 MCAsmBackend *MAB = nullptr;
Daniel Dunbar8f514a82010-12-16 03:06:05 +0000384 if (Opts.ShowEncoding) {
Eric Christophere0646e62015-03-10 22:03:27 +0000385 CE = TheTarget->createMCCodeEmitter(*MCII, *MRI, Ctx);
Joel Jonesb89eb652016-07-25 17:18:44 +0000386 MCTargetOptions Options;
387 MAB = TheTarget->createMCAsmBackend(*MRI, Opts.Triple, Opts.CPU, Options);
Daniel Dunbar8f514a82010-12-16 03:06:05 +0000388 }
Rafael Espindola4dedcd72015-04-09 21:06:11 +0000389 auto FOut = llvm::make_unique<formatted_raw_ostream>(*Out);
390 Str.reset(TheTarget->createAsmStreamer(
391 Ctx, std::move(FOut), /*asmverbose*/ true,
392 /*useDwarfDirectory*/ true, IP, CE, MAB, Opts.ShowInst));
Daniel Dunbar2fcaa542010-05-20 17:49:16 +0000393 } else if (Opts.OutputType == AssemblerInvocation::FT_Null) {
394 Str.reset(createNullStreamer(Ctx));
395 } else {
396 assert(Opts.OutputType == AssemblerInvocation::FT_Obj &&
397 "Invalid file type!");
Rafael Espindola2f16bc12015-04-14 15:15:49 +0000398 if (!FDOS->supportsSeeking()) {
399 BOS = make_unique<buffer_ostream>(*FDOS);
400 Out = BOS.get();
401 }
402
Eric Christophere0646e62015-03-10 22:03:27 +0000403 MCCodeEmitter *CE = TheTarget->createMCCodeEmitter(*MCII, *MRI, Ctx);
Joel Jonesb89eb652016-07-25 17:18:44 +0000404 MCTargetOptions Options;
Bill Wendling52575382013-09-09 02:37:56 +0000405 MCAsmBackend *MAB = TheTarget->createMCAsmBackend(*MRI, Opts.Triple,
Joel Jonesb89eb652016-07-25 17:18:44 +0000406 Opts.CPU, Options);
Daniel Sanders50f17232015-09-15 16:17:27 +0000407 Triple T(Opts.Triple);
David Majnemer2b9349d2015-12-21 22:09:34 +0000408 Str.reset(TheTarget->createMCObjectStreamer(
409 T, Ctx, *MAB, *Out, CE, *STI, Opts.RelaxAll,
410 Opts.IncrementalLinkerCompatible,
411 /*DWARFMustBeAtTheEnd*/ true));
Rafael Espindolad465be82014-10-15 16:12:57 +0000412 Str.get()->InitSections(Opts.NoExecStack);
Daniel Dunbar2fcaa542010-05-20 17:49:16 +0000413 }
414
Alp Toker44293142014-05-31 00:02:27 +0000415 bool Failed = false;
Alp Tokere98ea7c2014-05-31 00:02:21 +0000416
Ahmed Charlesb8984322014-03-07 20:03:18 +0000417 std::unique_ptr<MCAsmParser> Parser(
418 createMCAsmParser(SrcMgr, Ctx, *Str.get(), *MAI));
Evgeniy Stepanoveeb820f2014-04-23 11:15:49 +0000419
420 // FIXME: init MCTargetOptions from sanitizer flags here.
421 MCTargetOptions Options;
Ahmed Charlesb8984322014-03-07 20:03:18 +0000422 std::unique_ptr<MCTargetAsmParser> TAP(
Evgeniy Stepanoveeb820f2014-04-23 11:15:49 +0000423 TheTarget->createMCAsmParser(*STI, *Parser, *MCII, Options));
Alp Toker44293142014-05-31 00:02:27 +0000424 if (!TAP)
425 Failed = Diags.Report(diag::err_target_unknown_triple) << Opts.Triple;
Daniel Dunbar2fcaa542010-05-20 17:49:16 +0000426
Mandeep Singh Grang358faec2016-12-01 18:42:16 +0000427 // Set values for symbols, if any.
428 for (auto &S : Opts.SymbolDefs) {
429 if (Ctx.setSymbolValue(Parser->getStreamer(), S)) {
430 Failed = true;
431 break;
432 }
433 }
434
Alp Toker44293142014-05-31 00:02:27 +0000435 if (!Failed) {
Alp Tokere98ea7c2014-05-31 00:02:21 +0000436 Parser->setTargetParser(*TAP.get());
Alp Toker44293142014-05-31 00:02:27 +0000437 Failed = Parser->Run(Opts.NoInitialTextSection);
Alp Tokere98ea7c2014-05-31 00:02:21 +0000438 }
Daniel Dunbar2fcaa542010-05-20 17:49:16 +0000439
Steven Wuae480ec2015-07-24 02:12:43 +0000440 // Close Streamer first.
441 // It might have a reference to the output stream.
442 Str.reset();
Alp Tokere98ea7c2014-05-31 00:02:21 +0000443 // Close the output stream early.
Rafael Espindola2f16bc12015-04-14 15:15:49 +0000444 BOS.reset();
445 FDOS.reset();
Daniel Dunbar2fcaa542010-05-20 17:49:16 +0000446
Alp Tokere98ea7c2014-05-31 00:02:21 +0000447 // Delete output file if there were errors.
Alp Toker44293142014-05-31 00:02:27 +0000448 if (Failed && Opts.OutputPath != "-")
Rafael Espindolaccc6ea62013-06-26 12:48:34 +0000449 sys::fs::remove(Opts.OutputPath);
Daniel Dunbar2fcaa542010-05-20 17:49:16 +0000450
Alp Toker44293142014-05-31 00:02:27 +0000451 return Failed;
Daniel Dunbar2fcaa542010-05-20 17:49:16 +0000452}
453
Chad Rosier05c71aa2013-03-27 18:28:23 +0000454static void LLVMErrorHandler(void *UserData, const std::string &Message,
455 bool GenCrashDiag) {
David Blaikie9c902b52011-09-25 23:23:43 +0000456 DiagnosticsEngine &Diags = *static_cast<DiagnosticsEngine*>(UserData);
Daniel Dunbar2fcaa542010-05-20 17:49:16 +0000457
458 Diags.Report(diag::err_fe_error_backend) << Message;
459
460 // We cannot recover from llvm errors.
461 exit(1);
462}
463
Sean Silva070cd2d2014-08-15 21:38:36 +0000464int cc1as_main(ArrayRef<const char *> Argv, const char *Argv0, void *MainAddr) {
Daniel Dunbar2fcaa542010-05-20 17:49:16 +0000465 // Initialize targets and assembly printers/parsers.
466 InitializeAllTargetInfos();
Evan Chengc391a582011-07-22 21:59:11 +0000467 InitializeAllTargetMCs();
Daniel Dunbar2fcaa542010-05-20 17:49:16 +0000468 InitializeAllAsmParsers();
469
470 // Construct our diagnostic client.
Douglas Gregor811db4e2012-10-23 22:26:28 +0000471 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts = new DiagnosticOptions();
Douglas Gregor2dd19f12010-08-18 22:29:43 +0000472 TextDiagnosticPrinter *DiagClient
Douglas Gregor811db4e2012-10-23 22:26:28 +0000473 = new TextDiagnosticPrinter(errs(), &*DiagOpts);
Douglas Gregor2dd19f12010-08-18 22:29:43 +0000474 DiagClient->setPrefix("clang -cc1as");
Dylan Noblesmithc95d8192012-02-20 14:00:23 +0000475 IntrusiveRefCntPtr<DiagnosticIDs> DiagID(new DiagnosticIDs());
Douglas Gregor811db4e2012-10-23 22:26:28 +0000476 DiagnosticsEngine Diags(DiagID, &*DiagOpts, DiagClient);
Daniel Dunbar2fcaa542010-05-20 17:49:16 +0000477
478 // Set an error handler, so that any LLVM backend diagnostics go through our
479 // error handler.
Dan Gohmanb37af7d2010-08-18 21:23:17 +0000480 ScopedFatalErrorHandler FatalErrorHandler
481 (LLVMErrorHandler, static_cast<void*>(&Diags));
Daniel Dunbar2fcaa542010-05-20 17:49:16 +0000482
483 // Parse the arguments.
484 AssemblerInvocation Asm;
Sean Silva070cd2d2014-08-15 21:38:36 +0000485 if (!AssemblerInvocation::CreateFromArgs(Asm, Argv, Diags))
Dylan Noblesmithe99b27f2011-12-23 03:05:38 +0000486 return 1;
Daniel Dunbar2fcaa542010-05-20 17:49:16 +0000487
Daniel Dunbar0454f652010-05-20 18:15:20 +0000488 if (Asm.ShowHelp) {
Alp Toker61dad752014-07-09 14:05:11 +0000489 std::unique_ptr<OptTable> Opts(driver::createDriverOptTable());
Alp Toker532e5b92014-07-09 14:09:52 +0000490 Opts->PrintHelp(llvm::outs(), "clang -cc1as", "Clang Integrated Assembler",
491 /*Include=*/driver::options::CC1AsOption, /*Exclude=*/0);
Daniel Dunbar0454f652010-05-20 18:15:20 +0000492 return 0;
493 }
494
495 // Honor -version.
496 //
497 // FIXME: Use a better -version message?
498 if (Asm.ShowVersion) {
499 llvm::cl::PrintVersionMessage();
500 return 0;
501 }
502
503 // Honor -mllvm.
504 //
505 // FIXME: Remove this, one day.
506 if (!Asm.LLVMArgs.empty()) {
507 unsigned NumArgs = Asm.LLVMArgs.size();
508 const char **Args = new const char*[NumArgs + 2];
509 Args[0] = "clang (LLVM option parsing)";
510 for (unsigned i = 0; i != NumArgs; ++i)
511 Args[i + 1] = Asm.LLVMArgs[i].c_str();
Craig Topper69186e72014-06-08 08:38:04 +0000512 Args[NumArgs + 1] = nullptr;
David Blaikie09d20ee2012-02-07 19:36:38 +0000513 llvm::cl::ParseCommandLineOptions(NumArgs + 1, Args);
Daniel Dunbar0454f652010-05-20 18:15:20 +0000514 }
515
Daniel Dunbar2fcaa542010-05-20 17:49:16 +0000516 // Execute the invocation, unless there were parsing errors.
Alp Toker44293142014-05-31 00:02:27 +0000517 bool Failed = Diags.hasErrorOccurred() || ExecuteAssembler(Asm, Diags);
Daniel Dunbar2fcaa542010-05-20 17:49:16 +0000518
519 // If any timers were active but haven't been destroyed yet, print their
520 // results now.
521 TimerGroup::printAll(errs());
522
Alp Toker44293142014-05-31 00:02:27 +0000523 return !!Failed;
Daniel Dunbar2fcaa542010-05-20 17:49:16 +0000524}