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