cc1as_main.cpp revision 27e2b983beb8b5a29869639637327725623069a8
1//===-- 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" 16#include "clang/Basic/DiagnosticOptions.h" 17#include "clang/Driver/Arg.h" 18#include "clang/Driver/ArgList.h" 19#include "clang/Driver/CC1AsOptions.h" 20#include "clang/Driver/DriverDiagnostic.h" 21#include "clang/Driver/OptTable.h" 22#include "clang/Driver/Options.h" 23#include "clang/Frontend/FrontendDiagnostic.h" 24#include "clang/Frontend/TextDiagnosticPrinter.h" 25#include "llvm/ADT/OwningPtr.h" 26#include "llvm/ADT/StringSwitch.h" 27#include "llvm/ADT/Triple.h" 28#include "llvm/DataLayout.h" 29#include "llvm/MC/MCAsmBackend.h" 30#include "llvm/MC/MCAsmInfo.h" 31#include "llvm/MC/MCCodeEmitter.h" 32#include "llvm/MC/MCContext.h" 33#include "llvm/MC/MCInstrInfo.h" 34#include "llvm/MC/MCObjectFileInfo.h" 35#include "llvm/MC/MCParser/MCAsmParser.h" 36#include "llvm/MC/MCRegisterInfo.h" 37#include "llvm/MC/MCStreamer.h" 38#include "llvm/MC/MCSubtargetInfo.h" 39#include "llvm/MC/MCTargetAsmParser.h" 40#include "llvm/Support/CommandLine.h" 41#include "llvm/Support/ErrorHandling.h" 42#include "llvm/Support/FormattedStream.h" 43#include "llvm/Support/Host.h" 44#include "llvm/Support/ManagedStatic.h" 45#include "llvm/Support/MemoryBuffer.h" 46#include "llvm/Support/Path.h" 47#include "llvm/Support/PrettyStackTrace.h" 48#include "llvm/Support/Signals.h" 49#include "llvm/Support/SourceMgr.h" 50#include "llvm/Support/TargetRegistry.h" 51#include "llvm/Support/TargetSelect.h" 52#include "llvm/Support/Timer.h" 53#include "llvm/Support/raw_ostream.h" 54#include "llvm/Support/system_error.h" 55using namespace clang; 56using namespace clang::driver; 57using namespace llvm; 58 59namespace { 60 61/// \brief Helper class for representing a single invocation of the assembler. 62struct AssemblerInvocation { 63 /// @name Target Options 64 /// @{ 65 66 /// The name of the target triple to assemble for. 67 std::string Triple; 68 69 /// If given, the name of the target CPU to determine which instructions 70 /// are legal. 71 std::string CPU; 72 73 /// The list of target specific features to enable or disable -- this should 74 /// be a list of strings starting with '+' or '-'. 75 std::vector<std::string> Features; 76 77 /// @} 78 /// @name Language Options 79 /// @{ 80 81 std::vector<std::string> IncludePaths; 82 unsigned NoInitialTextSection : 1; 83 unsigned SaveTemporaryLabels : 1; 84 unsigned GenDwarfForAssembly : 1; 85 std::string DwarfDebugFlags; 86 std::string DebugCompilationDir; 87 std::string MainFileName; 88 89 /// @} 90 /// @name Frontend Options 91 /// @{ 92 93 std::string InputFile; 94 std::vector<std::string> LLVMArgs; 95 std::string OutputPath; 96 enum FileType { 97 FT_Asm, ///< Assembly (.s) output, transliterate mode. 98 FT_Null, ///< No output, for timing purposes. 99 FT_Obj ///< Object file output. 100 }; 101 FileType OutputType; 102 unsigned ShowHelp : 1; 103 unsigned ShowVersion : 1; 104 105 /// @} 106 /// @name Transliterate Options 107 /// @{ 108 109 unsigned OutputAsmVariant; 110 unsigned ShowEncoding : 1; 111 unsigned ShowInst : 1; 112 113 /// @} 114 /// @name Assembler Options 115 /// @{ 116 117 unsigned RelaxAll : 1; 118 unsigned NoExecStack : 1; 119 120 /// @} 121 122public: 123 AssemblerInvocation() { 124 Triple = ""; 125 NoInitialTextSection = 0; 126 InputFile = "-"; 127 OutputPath = "-"; 128 OutputType = FT_Asm; 129 OutputAsmVariant = 0; 130 ShowInst = 0; 131 ShowEncoding = 0; 132 RelaxAll = 0; 133 NoExecStack = 0; 134 } 135 136 static bool CreateFromArgs(AssemblerInvocation &Res, const char **ArgBegin, 137 const char **ArgEnd, DiagnosticsEngine &Diags); 138}; 139 140} 141 142bool AssemblerInvocation::CreateFromArgs(AssemblerInvocation &Opts, 143 const char **ArgBegin, 144 const char **ArgEnd, 145 DiagnosticsEngine &Diags) { 146 using namespace clang::driver::cc1asoptions; 147 bool Success = true; 148 149 // Parse the arguments. 150 OwningPtr<OptTable> OptTbl(createCC1AsOptTable()); 151 unsigned MissingArgIndex, MissingArgCount; 152 OwningPtr<InputArgList> Args( 153 OptTbl->ParseArgs(ArgBegin, ArgEnd,MissingArgIndex, MissingArgCount)); 154 155 // Check for missing argument error. 156 if (MissingArgCount) { 157 Diags.Report(diag::err_drv_missing_argument) 158 << Args->getArgString(MissingArgIndex) << MissingArgCount; 159 Success = false; 160 } 161 162 // Issue errors on unknown arguments. 163 for (arg_iterator it = Args->filtered_begin(cc1asoptions::OPT_UNKNOWN), 164 ie = Args->filtered_end(); it != ie; ++it) { 165 Diags.Report(diag::err_drv_unknown_argument) << (*it) ->getAsString(*Args); 166 Success = false; 167 } 168 169 // Construct the invocation. 170 171 // Target Options 172 Opts.Triple = llvm::Triple::normalize(Args->getLastArgValue(OPT_triple)); 173 Opts.CPU = Args->getLastArgValue(OPT_target_cpu); 174 Opts.Features = Args->getAllArgValues(OPT_target_feature); 175 176 // Use the default target triple if unspecified. 177 if (Opts.Triple.empty()) 178 Opts.Triple = llvm::sys::getDefaultTargetTriple(); 179 180 // Language Options 181 Opts.IncludePaths = Args->getAllArgValues(OPT_I); 182 Opts.NoInitialTextSection = Args->hasArg(OPT_n); 183 Opts.SaveTemporaryLabels = Args->hasArg(OPT_L); 184 Opts.GenDwarfForAssembly = Args->hasArg(OPT_g); 185 Opts.DwarfDebugFlags = Args->getLastArgValue(OPT_dwarf_debug_flags); 186 Opts.DebugCompilationDir = Args->getLastArgValue(OPT_fdebug_compilation_dir); 187 Opts.MainFileName = Args->getLastArgValue(OPT_main_file_name); 188 189 // Frontend Options 190 if (Args->hasArg(OPT_INPUT)) { 191 bool First = true; 192 for (arg_iterator it = Args->filtered_begin(OPT_INPUT), 193 ie = Args->filtered_end(); it != ie; ++it, First=false) { 194 const Arg *A = it; 195 if (First) 196 Opts.InputFile = A->getValue(); 197 else { 198 Diags.Report(diag::err_drv_unknown_argument) << A->getAsString(*Args); 199 Success = false; 200 } 201 } 202 } 203 Opts.LLVMArgs = Args->getAllArgValues(OPT_mllvm); 204 if (Args->hasArg(OPT_fatal_warnings)) 205 Opts.LLVMArgs.push_back("-fatal-assembler-warnings"); 206 Opts.OutputPath = Args->getLastArgValue(OPT_o); 207 if (Arg *A = Args->getLastArg(OPT_filetype)) { 208 StringRef Name = A->getValue(); 209 unsigned OutputType = StringSwitch<unsigned>(Name) 210 .Case("asm", FT_Asm) 211 .Case("null", FT_Null) 212 .Case("obj", FT_Obj) 213 .Default(~0U); 214 if (OutputType == ~0U) { 215 Diags.Report(diag::err_drv_invalid_value) 216 << A->getAsString(*Args) << Name; 217 Success = false; 218 } else 219 Opts.OutputType = FileType(OutputType); 220 } 221 Opts.ShowHelp = Args->hasArg(OPT_help); 222 Opts.ShowVersion = Args->hasArg(OPT_version); 223 224 // Transliterate Options 225 Opts.OutputAsmVariant = Args->getLastArgIntValue(OPT_output_asm_variant, 226 0, Diags); 227 Opts.ShowEncoding = Args->hasArg(OPT_show_encoding); 228 Opts.ShowInst = Args->hasArg(OPT_show_inst); 229 230 // Assemble Options 231 Opts.RelaxAll = Args->hasArg(OPT_relax_all); 232 Opts.NoExecStack = Args->hasArg(OPT_no_exec_stack); 233 234 return Success; 235} 236 237static formatted_raw_ostream *GetOutputStream(AssemblerInvocation &Opts, 238 DiagnosticsEngine &Diags, 239 bool Binary) { 240 if (Opts.OutputPath.empty()) 241 Opts.OutputPath = "-"; 242 243 // Make sure that the Out file gets unlinked from the disk if we get a 244 // SIGINT. 245 if (Opts.OutputPath != "-") 246 sys::RemoveFileOnSignal(sys::Path(Opts.OutputPath)); 247 248 std::string Error; 249 raw_fd_ostream *Out = 250 new raw_fd_ostream(Opts.OutputPath.c_str(), Error, 251 (Binary ? raw_fd_ostream::F_Binary : 0)); 252 if (!Error.empty()) { 253 Diags.Report(diag::err_fe_unable_to_open_output) 254 << Opts.OutputPath << Error; 255 return 0; 256 } 257 258 return new formatted_raw_ostream(*Out, formatted_raw_ostream::DELETE_STREAM); 259} 260 261static bool ExecuteAssembler(AssemblerInvocation &Opts, 262 DiagnosticsEngine &Diags) { 263 // Get the target specific parser. 264 std::string Error; 265 const Target *TheTarget(TargetRegistry::lookupTarget(Opts.Triple, Error)); 266 if (!TheTarget) { 267 Diags.Report(diag::err_target_unknown_triple) << Opts.Triple; 268 return false; 269 } 270 271 OwningPtr<MemoryBuffer> BufferPtr; 272 if (error_code ec = MemoryBuffer::getFileOrSTDIN(Opts.InputFile, BufferPtr)) { 273 Error = ec.message(); 274 Diags.Report(diag::err_fe_error_reading) << Opts.InputFile; 275 return false; 276 } 277 MemoryBuffer *Buffer = BufferPtr.take(); 278 279 SourceMgr SrcMgr; 280 281 // Tell SrcMgr about this buffer, which is what the parser will pick up. 282 SrcMgr.AddNewSourceBuffer(Buffer, SMLoc()); 283 284 // Record the location of the include directories so that the lexer can find 285 // it later. 286 SrcMgr.setIncludeDirs(Opts.IncludePaths); 287 288 OwningPtr<MCAsmInfo> MAI(TheTarget->createMCAsmInfo(Opts.Triple)); 289 assert(MAI && "Unable to create target asm info!"); 290 291 OwningPtr<MCRegisterInfo> MRI(TheTarget->createMCRegInfo(Opts.Triple)); 292 assert(MRI && "Unable to create target register info!"); 293 294 bool IsBinary = Opts.OutputType == AssemblerInvocation::FT_Obj; 295 formatted_raw_ostream *Out = GetOutputStream(Opts, Diags, IsBinary); 296 if (!Out) 297 return false; 298 299 // FIXME: This is not pretty. MCContext has a ptr to MCObjectFileInfo and 300 // MCObjectFileInfo needs a MCContext reference in order to initialize itself. 301 OwningPtr<MCObjectFileInfo> MOFI(new MCObjectFileInfo()); 302 MCContext Ctx(*MAI, *MRI, MOFI.get(), &SrcMgr); 303 // FIXME: Assembler behavior can change with -static. 304 MOFI->InitMCObjectFileInfo(Opts.Triple, 305 Reloc::Default, CodeModel::Default, Ctx); 306 if (Opts.SaveTemporaryLabels) 307 Ctx.setAllowTemporaryLabels(false); 308 if (Opts.GenDwarfForAssembly) 309 Ctx.setGenDwarfForAssembly(true); 310 if (!Opts.DwarfDebugFlags.empty()) 311 Ctx.setDwarfDebugFlags(StringRef(Opts.DwarfDebugFlags)); 312 if (!Opts.DebugCompilationDir.empty()) 313 Ctx.setCompilationDir(Opts.DebugCompilationDir); 314 if (!Opts.MainFileName.empty()) 315 Ctx.setMainFileName(StringRef(Opts.MainFileName)); 316 317 // Build up the feature string from the target feature list. 318 std::string FS; 319 if (!Opts.Features.empty()) { 320 FS = Opts.Features[0]; 321 for (unsigned i = 1, e = Opts.Features.size(); i != e; ++i) 322 FS += "," + Opts.Features[i]; 323 } 324 325 OwningPtr<MCStreamer> Str; 326 327 OwningPtr<MCInstrInfo> MCII(TheTarget->createMCInstrInfo()); 328 OwningPtr<MCSubtargetInfo> 329 STI(TheTarget->createMCSubtargetInfo(Opts.Triple, Opts.CPU, FS)); 330 331 // FIXME: There is a bit of code duplication with addPassesToEmitFile. 332 if (Opts.OutputType == AssemblerInvocation::FT_Asm) { 333 MCInstPrinter *IP = 334 TheTarget->createMCInstPrinter(Opts.OutputAsmVariant, *MAI, *MCII, *MRI, 335 *STI); 336 MCCodeEmitter *CE = 0; 337 MCAsmBackend *MAB = 0; 338 if (Opts.ShowEncoding) { 339 CE = TheTarget->createMCCodeEmitter(*MCII, *MRI, *STI, Ctx); 340 MAB = TheTarget->createMCAsmBackend(Opts.Triple, Opts.CPU); 341 } 342 Str.reset(TheTarget->createAsmStreamer(Ctx, *Out, /*asmverbose*/true, 343 /*useLoc*/ true, 344 /*useCFI*/ true, 345 /*useDwarfDirectory*/ true, 346 IP, CE, MAB, 347 Opts.ShowInst)); 348 } else if (Opts.OutputType == AssemblerInvocation::FT_Null) { 349 Str.reset(createNullStreamer(Ctx)); 350 } else { 351 assert(Opts.OutputType == AssemblerInvocation::FT_Obj && 352 "Invalid file type!"); 353 MCCodeEmitter *CE = TheTarget->createMCCodeEmitter(*MCII, *MRI, *STI, Ctx); 354 MCAsmBackend *MAB = TheTarget->createMCAsmBackend(Opts.Triple, Opts.CPU); 355 Str.reset(TheTarget->createMCObjectStreamer(Opts.Triple, Ctx, *MAB, *Out, 356 CE, Opts.RelaxAll, 357 Opts.NoExecStack)); 358 Str.get()->InitSections(); 359 } 360 361 OwningPtr<MCAsmParser> Parser(createMCAsmParser(SrcMgr, Ctx, 362 *Str.get(), *MAI)); 363 OwningPtr<MCTargetAsmParser> TAP(TheTarget->createMCAsmParser(*STI, *Parser)); 364 if (!TAP) { 365 Diags.Report(diag::err_target_unknown_triple) << Opts.Triple; 366 return false; 367 } 368 369 Parser->setTargetParser(*TAP.get()); 370 371 bool Success = !Parser->Run(Opts.NoInitialTextSection); 372 373 // Close the output. 374 delete Out; 375 376 // Delete output on errors. 377 if (!Success && Opts.OutputPath != "-") 378 sys::Path(Opts.OutputPath).eraseFromDisk(); 379 380 return Success; 381} 382 383static void LLVMErrorHandler(void *UserData, const std::string &Message) { 384 DiagnosticsEngine &Diags = *static_cast<DiagnosticsEngine*>(UserData); 385 386 Diags.Report(diag::err_fe_error_backend) << Message; 387 388 // We cannot recover from llvm errors. 389 exit(1); 390} 391 392int cc1as_main(const char **ArgBegin, const char **ArgEnd, 393 const char *Argv0, void *MainAddr) { 394 // Print a stack trace if we signal out. 395 sys::PrintStackTraceOnErrorSignal(); 396 PrettyStackTraceProgram X(ArgEnd - ArgBegin, ArgBegin); 397 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit. 398 399 // Initialize targets and assembly printers/parsers. 400 InitializeAllTargetInfos(); 401 InitializeAllTargetMCs(); 402 InitializeAllAsmParsers(); 403 404 // Construct our diagnostic client. 405 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts = new DiagnosticOptions(); 406 TextDiagnosticPrinter *DiagClient 407 = new TextDiagnosticPrinter(errs(), &*DiagOpts); 408 DiagClient->setPrefix("clang -cc1as"); 409 IntrusiveRefCntPtr<DiagnosticIDs> DiagID(new DiagnosticIDs()); 410 DiagnosticsEngine Diags(DiagID, &*DiagOpts, DiagClient); 411 412 // Set an error handler, so that any LLVM backend diagnostics go through our 413 // error handler. 414 ScopedFatalErrorHandler FatalErrorHandler 415 (LLVMErrorHandler, static_cast<void*>(&Diags)); 416 417 // Parse the arguments. 418 AssemblerInvocation Asm; 419 if (!AssemblerInvocation::CreateFromArgs(Asm, ArgBegin, ArgEnd, Diags)) 420 return 1; 421 422 // Honor -help. 423 if (Asm.ShowHelp) { 424 OwningPtr<driver::OptTable> Opts(driver::createCC1AsOptTable()); 425 Opts->PrintHelp(llvm::outs(), "clang -cc1as", "Clang Integrated Assembler"); 426 return 0; 427 } 428 429 // Honor -version. 430 // 431 // FIXME: Use a better -version message? 432 if (Asm.ShowVersion) { 433 llvm::cl::PrintVersionMessage(); 434 return 0; 435 } 436 437 // Honor -mllvm. 438 // 439 // FIXME: Remove this, one day. 440 if (!Asm.LLVMArgs.empty()) { 441 unsigned NumArgs = Asm.LLVMArgs.size(); 442 const char **Args = new const char*[NumArgs + 2]; 443 Args[0] = "clang (LLVM option parsing)"; 444 for (unsigned i = 0; i != NumArgs; ++i) 445 Args[i + 1] = Asm.LLVMArgs[i].c_str(); 446 Args[NumArgs + 1] = 0; 447 llvm::cl::ParseCommandLineOptions(NumArgs + 1, Args); 448 } 449 450 // Execute the invocation, unless there were parsing errors. 451 bool Success = false; 452 if (!Diags.hasErrorOccurred()) 453 Success = ExecuteAssembler(Asm, Diags); 454 455 // If any timers were active but haven't been destroyed yet, print their 456 // results now. 457 TimerGroup::printAll(errs()); 458 459 return !Success; 460} 461