Initialize the target architecture based on compiler defines, so if compiled on
[oota-llvm.git] / tools / llc / llc.cpp
1 //===-- llc.cpp - Implement the LLVM Native Code Generator ----------------===//
2 //
3 // This is the llc code generator.
4 //
5 //===----------------------------------------------------------------------===//
6
7 #include "llvm/Bytecode/Reader.h"
8 #include "llvm/Target/TargetMachineImpls.h"
9 #include "llvm/Target/TargetMachine.h"
10 #include "llvm/Transforms/Scalar.h"
11 #include "llvm/Module.h"
12 #include "llvm/PassManager.h"
13 #include "llvm/Pass.h"
14 #include "Support/CommandLine.h"
15 #include "Support/Signals.h"
16 #include <memory>
17 #include <fstream>
18
19 // General options for llc.  Other pass-specific options are specified
20 // within the corresponding llc passes, and target-specific options
21 // and back-end code generation options are specified with the target machine.
22 // 
23 static cl::opt<std::string>
24 InputFilename(cl::Positional, cl::desc("<input bytecode>"), cl::init("-"));
25
26 static cl::opt<std::string>
27 OutputFilename("o", cl::desc("Output filename"), cl::value_desc("filename"));
28
29 static cl::opt<bool> Force("f", cl::desc("Overwrite output files"));
30
31 enum ArchName { noarch, x86, Sparc };
32
33 static cl::opt<ArchName>
34 Arch("march", cl::desc("Architecture to generate assembly for:"), cl::Prefix,
35      cl::values(clEnumVal(x86, "  IA-32 (Pentium and above)"),
36                 clEnumValN(Sparc, "sparc", "  SPARC V9"),
37                 0),
38 #if defined(i386) || defined(__i386__) || defined(__x86__)
39      cl::init(x86)
40 #elif defined(sparc) || defined(__sparc__) || defined(__sparcv9)
41      cl::init(Sparc)
42 #else
43      cl::init(noarch)
44 #endif
45      );
46
47 // GetFileNameRoot - Helper function to get the basename of a filename...
48 static inline std::string
49 GetFileNameRoot(const std::string &InputFilename)
50 {
51   std::string IFN = InputFilename;
52   std::string outputFilename;
53   int Len = IFN.length();
54   if (IFN[Len-3] == '.' && IFN[Len-2] == 'b' && IFN[Len-1] == 'c') {
55     outputFilename = std::string(IFN.begin(), IFN.end()-3); // s/.bc/.s/
56   } else {
57     outputFilename = IFN;
58   }
59   return outputFilename;
60 }
61
62
63 // main - Entry point for the llc compiler.
64 //
65 int main(int argc, char **argv) {
66   cl::ParseCommandLineOptions(argc, argv, " llvm system compiler\n");
67   
68   // Load the module to be compiled...
69   std::auto_ptr<Module> M(ParseBytecodeFile(InputFilename));
70   if (M.get() == 0) {
71     std::cerr << argv[0] << ": bytecode didn't read correctly.\n";
72     return 1;
73   }
74   Module &mod = *M.get();
75
76   // Allocate target machine.  First, check whether the user has
77   // explicitly specified an architecture to compile for.
78   unsigned Config = (mod.isLittleEndian()   ? TM::LittleEndian : TM::BigEndian)|
79                     (mod.has32BitPointers() ? TM::PtrSize32    : TM::PtrSize64);
80   TargetMachine* (*TargetMachineAllocator)(unsigned) = 0;
81   switch (Arch) {
82   case x86:
83     TargetMachineAllocator = allocateX86TargetMachine;
84     break;
85   case Sparc:
86     TargetMachineAllocator = allocateSparcTargetMachine;
87     break;
88   default:
89     // Decide what the default target machine should be, by looking at
90     // the module. This heuristic (ILP32, LE -> IA32; LP64, BE ->
91     // SPARCV9) is kind of gross, but it will work until we have more
92     // sophisticated target information to work from.
93     if (mod.isLittleEndian() && mod.has32BitPointers()) { 
94       TargetMachineAllocator = allocateX86TargetMachine;
95     } else if (mod.isBigEndian() && mod.has64BitPointers()) {
96       TargetMachineAllocator = allocateSparcTargetMachine;
97     } else {
98       assert(0 && "You must specify -march; I could not guess the default");
99     } 
100     break;
101   }
102   std::auto_ptr<TargetMachine> target((*TargetMachineAllocator)(Config));
103   assert(target.get() && "Could not allocate target machine!");
104   TargetMachine &Target = *target.get();
105   const TargetData &TD = Target.getTargetData();
106
107   // Build up all of the passes that we want to do to the module...
108   PassManager Passes;
109
110   Passes.add(new TargetData("llc", TD.isLittleEndian(), TD.getPointerSize(),
111                             TD.getPointerAlignment(), TD.getDoubleAlignment()));
112
113   // Figure out where we are going to send the output...
114   std::ostream *Out = 0;
115   if (OutputFilename != "") {
116     if (OutputFilename != "-") {
117       // Specified an output filename?
118       if (!Force && std::ifstream(OutputFilename.c_str())) {
119         // If force is not specified, make sure not to overwrite a file!
120         std::cerr << argv[0] << ": error opening '" << OutputFilename
121                   << "': file exists!\n"
122                   << "Use -f command line argument to force output\n";
123         return 1;
124       }
125       Out = new std::ofstream(OutputFilename.c_str());
126
127       // Make sure that the Out file gets unlink'd from the disk if we get a
128       // SIGINT
129       RemoveFileOnSignal(OutputFilename);
130     } else {
131       Out = &std::cout;
132     }
133   } else {
134     if (InputFilename == "-") {
135       OutputFilename = "-";
136       Out = &std::cout;
137     } else {
138       OutputFilename = GetFileNameRoot(InputFilename); 
139       OutputFilename += ".s";
140       
141       if (!Force && std::ifstream(OutputFilename.c_str())) {
142         // If force is not specified, make sure not to overwrite a file!
143         std::cerr << argv[0] << ": error opening '" << OutputFilename
144                   << "': file exists!\n"
145                   << "Use -f command line argument to force output\n";
146         return 1;
147       }
148       
149       Out = new std::ofstream(OutputFilename.c_str());
150       if (!Out->good()) {
151         std::cerr << argv[0] << ": error opening " << OutputFilename << "!\n";
152         delete Out;
153         return 1;
154       }
155       
156       // Make sure that the Out file gets unlink'd from the disk if we get a
157       // SIGINT
158       RemoveFileOnSignal(OutputFilename);
159     }
160   }
161
162   // Ask the target to add backend passes as necessary
163   if (Target.addPassesToEmitAssembly(Passes, *Out)) {
164     std::cerr << argv[0] << ": target '" << Target.getName()
165               << "' does not support static compilation!\n";
166     if (Out != &std::cout) delete Out;
167     // And the Out file is empty and useless, so remove it now.
168     std::remove(OutputFilename.c_str());
169     return 1;
170   } else {
171     // Run our queue of passes all at once now, efficiently.
172     Passes.run(*M.get());
173   }
174
175   // Delete the ostream if it's not a stdout stream
176   if (Out != &std::cout) delete Out;
177
178   return 0;
179 }