1 //===-- llc.cpp - Implement the LLVM Native Code Generator ----------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This is the llc code generator driver. It provides a convenient
11 // command-line interface for generating native assembly-language code
12 // or C code, given LLVM bitcode.
14 //===----------------------------------------------------------------------===//
16 #include "llvm/Bitcode/ReaderWriter.h"
17 #include "llvm/CodeGen/FileWriters.h"
18 #include "llvm/CodeGen/LinkAllCodegenComponents.h"
19 #include "llvm/CodeGen/LinkAllAsmWriterComponents.h"
20 #include "llvm/Target/SubtargetFeature.h"
21 #include "llvm/Target/TargetData.h"
22 #include "llvm/Target/TargetMachine.h"
23 #include "llvm/Target/TargetMachineRegistry.h"
24 #include "llvm/Transforms/Scalar.h"
25 #include "llvm/Module.h"
26 #include "llvm/ModuleProvider.h"
27 #include "llvm/PassManager.h"
28 #include "llvm/Pass.h"
29 #include "llvm/Support/CommandLine.h"
30 #include "llvm/Support/FileUtilities.h"
31 #include "llvm/Support/ManagedStatic.h"
32 #include "llvm/Support/MemoryBuffer.h"
33 #include "llvm/Support/PluginLoader.h"
34 #include "llvm/Support/RegistryParser.h"
35 #include "llvm/Support/raw_ostream.h"
36 #include "llvm/Analysis/Verifier.h"
37 #include "llvm/System/Signals.h"
38 #include "llvm/Config/config.h"
39 #include "llvm/LinkAllVMCore.h"
45 // General options for llc. Other pass-specific options are specified
46 // within the corresponding llc passes, and target-specific options
47 // and back-end code generation options are specified with the target machine.
49 static cl::opt<std::string>
50 InputFilename(cl::Positional, cl::desc("<input bitcode>"), cl::init("-"));
52 static cl::opt<std::string>
53 OutputFilename("o", cl::desc("Output filename"), cl::value_desc("filename"));
55 static cl::opt<bool> Force("f", cl::desc("Overwrite output files"));
57 static cl::opt<bool> Fast("fast",
58 cl::desc("Generate code quickly, potentially sacrificing code quality"));
60 static cl::opt<std::string>
61 TargetTriple("mtriple", cl::desc("Override target triple for module"));
63 static cl::opt<const TargetMachineRegistry::entry*, false,
64 RegistryParser<TargetMachine> >
65 MArch("march", cl::desc("Architecture to generate code for:"));
67 static cl::opt<std::string>
69 cl::desc("Target a specific cpu type (-mcpu=help for details)"),
70 cl::value_desc("cpu-name"),
73 static cl::list<std::string>
76 cl::desc("Target specific attributes (-mattr=help for details)"),
77 cl::value_desc("a1,+a2,-a3,..."));
79 cl::opt<TargetMachine::CodeGenFileType>
80 FileType("filetype", cl::init(TargetMachine::AssemblyFile),
81 cl::desc("Choose a file type (not all types are supported by all targets):"),
83 clEnumValN(TargetMachine::AssemblyFile, "asm",
84 "Emit an assembly ('.s') file"),
85 clEnumValN(TargetMachine::ObjectFile, "obj",
86 "Emit a native object ('.o') file [experimental]"),
87 clEnumValN(TargetMachine::DynamicLibrary, "dynlib",
88 "Emit a native dynamic library ('.so') file"
92 cl::opt<bool> NoVerify("disable-verify", cl::Hidden,
93 cl::desc("Do not verify input module"));
96 // GetFileNameRoot - Helper function to get the basename of a filename.
97 static inline std::string
98 GetFileNameRoot(const std::string &InputFilename) {
99 std::string IFN = InputFilename;
100 std::string outputFilename;
101 int Len = IFN.length();
103 IFN[Len-3] == '.' && IFN[Len-2] == 'b' && IFN[Len-1] == 'c') {
104 outputFilename = std::string(IFN.begin(), IFN.end()-3); // s/.bc/.s/
106 outputFilename = IFN;
108 return outputFilename;
111 static raw_ostream *GetOutputStream(const char *ProgName) {
112 if (OutputFilename != "") {
113 if (OutputFilename == "-")
116 // Specified an output filename?
117 if (!Force && std::ifstream(OutputFilename.c_str())) {
118 // If force is not specified, make sure not to overwrite a file!
119 std::cerr << ProgName << ": error opening '" << OutputFilename
120 << "': file exists!\n"
121 << "Use -f command line argument to force output\n";
124 // Make sure that the Out file gets unlinked from the disk if we get a
126 sys::RemoveFileOnSignal(sys::Path(OutputFilename));
129 raw_ostream *Out = new raw_fd_ostream(OutputFilename.c_str(), true, error);
130 if (!error.empty()) {
131 std::cerr << error << '\n';
139 if (InputFilename == "-") {
140 OutputFilename = "-";
144 OutputFilename = GetFileNameRoot(InputFilename);
148 case TargetMachine::AssemblyFile:
149 if (MArch->Name[0] == 'c') {
150 if (MArch->Name[1] == 0)
151 OutputFilename += ".cbe.c";
152 else if (MArch->Name[1] == 'p' && MArch->Name[2] == 'p')
153 OutputFilename += ".cpp";
155 OutputFilename += ".s";
157 OutputFilename += ".s";
159 case TargetMachine::ObjectFile:
160 OutputFilename += ".o";
163 case TargetMachine::DynamicLibrary:
164 OutputFilename += LTDL_SHLIB_EXT;
169 if (!Force && std::ifstream(OutputFilename.c_str())) {
170 // If force is not specified, make sure not to overwrite a file!
171 std::cerr << ProgName << ": error opening '" << OutputFilename
172 << "': file exists!\n"
173 << "Use -f command line argument to force output\n";
177 // Make sure that the Out file gets unlinked from the disk if we get a
179 sys::RemoveFileOnSignal(sys::Path(OutputFilename));
182 raw_ostream *Out = new raw_fd_ostream(OutputFilename.c_str(), Binary, error);
183 if (!error.empty()) {
184 std::cerr << error << '\n';
192 // main - Entry point for the llc compiler.
194 int main(int argc, char **argv) {
195 llvm_shutdown_obj X; // Call llvm_shutdown() on exit.
196 cl::ParseCommandLineOptions(argc, argv, "llvm system compiler\n");
197 sys::PrintStackTraceOnErrorSignal();
199 // Load the module to be compiled...
200 std::string ErrorMessage;
201 std::auto_ptr<Module> M;
203 std::auto_ptr<MemoryBuffer> Buffer(
204 MemoryBuffer::getFileOrSTDIN(InputFilename, &ErrorMessage));
206 M.reset(ParseBitcodeFile(Buffer.get(), &ErrorMessage));
208 std::cerr << argv[0] << ": bitcode didn't read correctly.\n";
209 std::cerr << "Reason: " << ErrorMessage << "\n";
212 Module &mod = *M.get();
214 // If we are supposed to override the target triple, do so now.
215 if (!TargetTriple.empty())
216 mod.setTargetTriple(TargetTriple);
218 // Allocate target machine. First, check whether the user has
219 // explicitly specified an architecture to compile for.
222 MArch = TargetMachineRegistry::getClosestStaticTargetForModule(mod, Err);
224 std::cerr << argv[0] << ": error auto-selecting target for module '"
225 << Err << "'. Please use the -march option to explicitly "
226 << "pick a target.\n";
231 // Package up features to be passed to target/subtarget
232 std::string FeaturesStr;
233 if (MCPU.size() || MAttrs.size()) {
234 SubtargetFeatures Features;
235 Features.setCPU(MCPU);
236 for (unsigned i = 0; i != MAttrs.size(); ++i)
237 Features.AddFeature(MAttrs[i]);
238 FeaturesStr = Features.getString();
241 std::auto_ptr<TargetMachine> target(MArch->CtorFn(mod, FeaturesStr));
242 assert(target.get() && "Could not allocate target machine!");
243 TargetMachine &Target = *target.get();
245 // Figure out where we are going to send the output...
246 raw_ostream *Out = GetOutputStream(argv[0]);
247 if (Out == 0) return 1;
249 // If this target requires addPassesToEmitWholeFile, do it now. This is
250 // used by strange things like the C backend.
251 if (Target.WantsWholeFile()) {
253 PM.add(new TargetData(*Target.getTargetData()));
255 PM.add(createVerifierPass());
257 // Ask the target to add backend passes as necessary.
258 if (Target.addPassesToEmitWholeFile(PM, *Out, FileType, Fast)) {
259 std::cerr << argv[0] << ": target does not support generation of this"
261 if (Out != &outs()) delete Out;
262 // And the Out file is empty and useless, so remove it now.
263 sys::Path(OutputFilename).eraseFromDisk();
268 // Build up all of the passes that we want to do to the module.
269 ExistingModuleProvider Provider(M.release());
270 FunctionPassManager Passes(&Provider);
271 Passes.add(new TargetData(*Target.getTargetData()));
275 Passes.add(createVerifierPass());
278 // Ask the target to add backend passes as necessary.
279 MachineCodeEmitter *MCE = 0;
281 switch (Target.addPassesToEmitFile(Passes, *Out, FileType, Fast)) {
283 assert(0 && "Invalid file model!");
285 case FileModel::Error:
286 std::cerr << argv[0] << ": target does not support generation of this"
288 if (Out != &outs()) delete Out;
289 // And the Out file is empty and useless, so remove it now.
290 sys::Path(OutputFilename).eraseFromDisk();
292 case FileModel::AsmFile:
294 case FileModel::MachOFile:
295 MCE = AddMachOWriter(Passes, *Out, Target);
297 case FileModel::ElfFile:
298 MCE = AddELFWriter(Passes, *Out, Target);
302 if (Target.addPassesToEmitFileFinish(Passes, MCE, Fast)) {
303 std::cerr << argv[0] << ": target does not support generation of this"
305 if (Out != &outs()) delete Out;
306 // And the Out file is empty and useless, so remove it now.
307 sys::Path(OutputFilename).eraseFromDisk();
311 Passes.doInitialization();
313 // Run our queue of passes all at once now, efficiently.
314 // TODO: this could lazily stream functions out of the module.
315 for (Module::iterator I = mod.begin(), E = mod.end(); I != E; ++I)
316 if (!I->isDeclaration())
319 Passes.doFinalization();
322 // Delete the ostream if it's not a stdout stream
323 if (Out != &outs()) delete Out;