Remove VISIBILITY_HIDDEN from this file.
[llvm/avr.git] / tools / llvm-mc / llvm-mc.cpp
blobfd0316460b620fa1ed1ce6d24549d65fbb19ba6d
1 //===-- llvm-mc.cpp - Machine Code Hacking Driver -------------------------===//
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 utility is a simple driver that allows command line hacking on machine
11 // code.
13 //===----------------------------------------------------------------------===//
15 #include "llvm/MC/MCContext.h"
16 #include "llvm/MC/MCCodeEmitter.h"
17 #include "llvm/MC/MCSectionMachO.h"
18 #include "llvm/MC/MCStreamer.h"
19 #include "llvm/ADT/OwningPtr.h"
20 #include "llvm/CodeGen/AsmPrinter.h"
21 #include "llvm/Support/CommandLine.h"
22 #include "llvm/Support/FormattedStream.h"
23 #include "llvm/Support/ManagedStatic.h"
24 #include "llvm/Support/MemoryBuffer.h"
25 #include "llvm/Support/PrettyStackTrace.h"
26 #include "llvm/Support/SourceMgr.h"
27 #include "llvm/Support/raw_ostream.h"
28 #include "llvm/System/Signals.h"
29 #include "llvm/Target/TargetAsmParser.h"
30 #include "llvm/Target/TargetRegistry.h"
31 #include "llvm/Target/TargetSelect.h"
32 #include "AsmParser.h"
33 using namespace llvm;
35 static cl::opt<std::string>
36 InputFilename(cl::Positional, cl::desc("<input file>"), cl::init("-"));
38 static cl::opt<std::string>
39 OutputFilename("o", cl::desc("Output filename"),
40 cl::value_desc("filename"));
42 static cl::opt<bool>
43 ShowEncoding("show-encoding", cl::desc("Show instruction encodings"));
45 enum OutputFileType {
46 OFT_AssemblyFile,
47 OFT_ObjectFile
49 static cl::opt<OutputFileType>
50 FileType("filetype", cl::init(OFT_AssemblyFile),
51 cl::desc("Choose an output file type:"),
52 cl::values(
53 clEnumValN(OFT_AssemblyFile, "asm",
54 "Emit an assembly ('.s') file"),
55 clEnumValN(OFT_ObjectFile, "obj",
56 "Emit a native object ('.o') file"),
57 clEnumValEnd));
59 static cl::opt<bool>
60 Force("f", cl::desc("Enable binary output on terminals"));
62 static cl::list<std::string>
63 IncludeDirs("I", cl::desc("Directory of include files"),
64 cl::value_desc("directory"), cl::Prefix);
66 static cl::opt<std::string>
67 TripleName("triple", cl::desc("Target triple to assemble for,"
68 "see -version for available targets"),
69 cl::init(LLVM_HOSTTRIPLE));
71 enum ActionType {
72 AC_AsLex,
73 AC_Assemble
76 static cl::opt<ActionType>
77 Action(cl::desc("Action to perform:"),
78 cl::init(AC_Assemble),
79 cl::values(clEnumValN(AC_AsLex, "as-lex",
80 "Lex tokens from a .s file"),
81 clEnumValN(AC_Assemble, "assemble",
82 "Assemble a .s file (default)"),
83 clEnumValEnd));
85 static int AsLexInput(const char *ProgName) {
86 std::string ErrorMessage;
87 MemoryBuffer *Buffer = MemoryBuffer::getFileOrSTDIN(InputFilename,
88 &ErrorMessage);
89 if (Buffer == 0) {
90 errs() << ProgName << ": ";
91 if (ErrorMessage.size())
92 errs() << ErrorMessage << "\n";
93 else
94 errs() << "input file didn't read correctly.\n";
95 return 1;
98 SourceMgr SrcMgr;
100 // Tell SrcMgr about this buffer, which is what TGParser will pick up.
101 SrcMgr.AddNewSourceBuffer(Buffer, SMLoc());
103 // Record the location of the include directories so that the lexer can find
104 // it later.
105 SrcMgr.setIncludeDirs(IncludeDirs);
107 AsmLexer Lexer(SrcMgr);
109 bool Error = false;
111 while (Lexer.Lex().isNot(AsmToken::Eof)) {
112 switch (Lexer.getKind()) {
113 default:
114 Lexer.PrintMessage(Lexer.getLoc(), "unknown token", "warning");
115 Error = true;
116 break;
117 case AsmToken::Error:
118 Error = true; // error already printed.
119 break;
120 case AsmToken::Identifier:
121 outs() << "identifier: " << Lexer.getTok().getString() << '\n';
122 break;
123 case AsmToken::Register:
124 outs() << "register: " << Lexer.getTok().getString() << '\n';
125 break;
126 case AsmToken::String:
127 outs() << "string: " << Lexer.getTok().getString() << '\n';
128 break;
129 case AsmToken::Integer:
130 outs() << "int: " << Lexer.getTok().getString() << '\n';
131 break;
133 case AsmToken::Amp: outs() << "Amp\n"; break;
134 case AsmToken::AmpAmp: outs() << "AmpAmp\n"; break;
135 case AsmToken::Caret: outs() << "Caret\n"; break;
136 case AsmToken::Colon: outs() << "Colon\n"; break;
137 case AsmToken::Comma: outs() << "Comma\n"; break;
138 case AsmToken::Dollar: outs() << "Dollar\n"; break;
139 case AsmToken::EndOfStatement: outs() << "EndOfStatement\n"; break;
140 case AsmToken::Eof: outs() << "Eof\n"; break;
141 case AsmToken::Equal: outs() << "Equal\n"; break;
142 case AsmToken::EqualEqual: outs() << "EqualEqual\n"; break;
143 case AsmToken::Exclaim: outs() << "Exclaim\n"; break;
144 case AsmToken::ExclaimEqual: outs() << "ExclaimEqual\n"; break;
145 case AsmToken::Greater: outs() << "Greater\n"; break;
146 case AsmToken::GreaterEqual: outs() << "GreaterEqual\n"; break;
147 case AsmToken::GreaterGreater: outs() << "GreaterGreater\n"; break;
148 case AsmToken::LParen: outs() << "LParen\n"; break;
149 case AsmToken::Less: outs() << "Less\n"; break;
150 case AsmToken::LessEqual: outs() << "LessEqual\n"; break;
151 case AsmToken::LessGreater: outs() << "LessGreater\n"; break;
152 case AsmToken::LessLess: outs() << "LessLess\n"; break;
153 case AsmToken::Minus: outs() << "Minus\n"; break;
154 case AsmToken::Percent: outs() << "Percent\n"; break;
155 case AsmToken::Pipe: outs() << "Pipe\n"; break;
156 case AsmToken::PipePipe: outs() << "PipePipe\n"; break;
157 case AsmToken::Plus: outs() << "Plus\n"; break;
158 case AsmToken::RParen: outs() << "RParen\n"; break;
159 case AsmToken::Slash: outs() << "Slash\n"; break;
160 case AsmToken::Star: outs() << "Star\n"; break;
161 case AsmToken::Tilde: outs() << "Tilde\n"; break;
165 return Error;
168 static const Target *GetTarget(const char *ProgName) {
169 // Get the target specific parser.
170 std::string Error;
171 const Target *TheTarget = TargetRegistry::lookupTarget(TripleName, Error);
172 if (TheTarget)
173 return TheTarget;
175 errs() << ProgName << ": error: unable to get target for '" << TripleName
176 << "', see --version and --triple.\n";
177 return 0;
180 static formatted_raw_ostream *GetOutputStream() {
181 if (OutputFilename == "")
182 OutputFilename = "-";
184 // Make sure that the Out file gets unlinked from the disk if we get a
185 // SIGINT.
186 if (OutputFilename != "-")
187 sys::RemoveFileOnSignal(sys::Path(OutputFilename));
189 std::string Err;
190 raw_fd_ostream *Out = new raw_fd_ostream(OutputFilename.c_str(), Err,
191 raw_fd_ostream::F_Binary);
192 if (!Err.empty()) {
193 errs() << Err << '\n';
194 delete Out;
195 return 0;
198 return new formatted_raw_ostream(*Out, formatted_raw_ostream::DELETE_STREAM);
201 static int AssembleInput(const char *ProgName) {
202 const Target *TheTarget = GetTarget(ProgName);
203 if (!TheTarget)
204 return 1;
206 std::string Error;
207 MemoryBuffer *Buffer = MemoryBuffer::getFileOrSTDIN(InputFilename, &Error);
208 if (Buffer == 0) {
209 errs() << ProgName << ": ";
210 if (Error.size())
211 errs() << Error << "\n";
212 else
213 errs() << "input file didn't read correctly.\n";
214 return 1;
217 SourceMgr SrcMgr;
219 // Tell SrcMgr about this buffer, which is what the parser will pick up.
220 SrcMgr.AddNewSourceBuffer(Buffer, SMLoc());
222 // Record the location of the include directories so that the lexer can find
223 // it later.
224 SrcMgr.setIncludeDirs(IncludeDirs);
226 MCContext Ctx;
227 formatted_raw_ostream *Out = GetOutputStream();
228 if (!Out)
229 return 1;
232 // FIXME: We shouldn't need to do this (and link in codegen).
233 OwningPtr<TargetMachine> TM(TheTarget->createTargetMachine(TripleName, ""));
235 if (!TM) {
236 errs() << ProgName << ": error: could not create target for triple '"
237 << TripleName << "'.\n";
238 return 1;
241 OwningPtr<AsmPrinter> AP;
242 OwningPtr<MCCodeEmitter> CE;
243 OwningPtr<MCStreamer> Str;
245 if (FileType == OFT_AssemblyFile) {
246 const MCAsmInfo *MAI = TheTarget->createAsmInfo(TripleName);
247 assert(MAI && "Unable to create target asm info!");
249 AP.reset(TheTarget->createAsmPrinter(*Out, *TM, MAI, true));
250 if (ShowEncoding)
251 CE.reset(TheTarget->createCodeEmitter(*TM));
252 Str.reset(createAsmStreamer(Ctx, *Out, *MAI, AP.get(), CE.get()));
253 } else {
254 assert(FileType == OFT_ObjectFile && "Invalid file type!");
255 CE.reset(TheTarget->createCodeEmitter(*TM));
256 Str.reset(createMachOStreamer(Ctx, *Out, CE.get()));
259 AsmParser Parser(SrcMgr, Ctx, *Str.get());
260 OwningPtr<TargetAsmParser> TAP(TheTarget->createAsmParser(Parser));
261 if (!TAP) {
262 errs() << ProgName
263 << ": error: this target does not support assembly parsing.\n";
264 return 1;
267 Parser.setTargetParser(*TAP.get());
269 int Res = Parser.Run();
270 if (Out != &fouts())
271 delete Out;
273 return Res;
277 int main(int argc, char **argv) {
278 // Print a stack trace if we signal out.
279 sys::PrintStackTraceOnErrorSignal();
280 PrettyStackTraceProgram X(argc, argv);
281 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
283 // Initialize targets and assembly printers/parsers.
284 llvm::InitializeAllTargetInfos();
285 // FIXME: We shouldn't need to initialize the Target(Machine)s.
286 llvm::InitializeAllTargets();
287 llvm::InitializeAllAsmPrinters();
288 llvm::InitializeAllAsmParsers();
290 cl::ParseCommandLineOptions(argc, argv, "llvm machine code playground\n");
292 switch (Action) {
293 default:
294 case AC_AsLex:
295 return AsLexInput(argv[0]);
296 case AC_Assemble:
297 return AssembleInput(argv[0]);
300 return 0;