blob: 182397a27e79575892f9c6f6a690d9f602518ccb [file] [log] [blame]
Reid Spencera3f18552004-08-13 20:25:54 +00001//===- CompilerDriver.cpp - The LLVM Compiler Driver ------------*- C++ -*-===//
Reid Spencer5c56dc12004-08-13 20:22:43 +00002//
3//
4// The LLVM Compiler Infrastructure
5//
6// This file was developed by Reid Spencer and is distributed under the
7// University of Illinois Open Source License. See LICENSE.TXT for details.
8//
9//===----------------------------------------------------------------------===//
10//
Reid Spencera3f18552004-08-13 20:25:54 +000011// This file implements the bulk of the LLVM Compiler Driver (llvmc).
Reid Spencer5c56dc12004-08-13 20:22:43 +000012//
13//===------------------------------------------------------------------------===
14
15#include "CompilerDriver.h"
Reid Spencerbf437722004-08-15 08:19:46 +000016#include "ConfigLexer.h"
Reid Spencera01439a2004-08-24 13:55:17 +000017#include "llvm/Module.h"
Reid Spencer52c2dc12004-08-29 19:26:56 +000018#include "llvm/Bytecode/Reader.h"
Reid Spencer54fafe42004-09-14 01:58:45 +000019#include "llvm/Support/Timer.h"
Reid Spencer93426ba2004-08-29 20:02:28 +000020#include "llvm/System/Signals.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000021#include "llvm/ADT/SetVector.h"
22#include "llvm/ADT/StringExtras.h"
Reid Spencer5c56dc12004-08-13 20:22:43 +000023#include <iostream>
24
25using namespace llvm;
26
27namespace {
Reid Spencer5c56dc12004-08-13 20:22:43 +000028
Reid Spenceraf77d742004-10-28 04:05:06 +000029void WriteAction(CompilerDriver::Action* action ) {
30 std::cerr << action->program.c_str();
31 std::vector<std::string>::iterator I = action->args.begin();
32 while (I != action->args.end()) {
33 std::cerr << " " + *I;
34 ++I;
35 }
36 std::cerr << "\n";
37}
38
39void DumpAction(CompilerDriver::Action* action) {
40 std::cerr << "command = " << action->program.c_str();
41 std::vector<std::string>::iterator I = action->args.begin();
42 while (I != action->args.end()) {
43 std::cerr << " " + *I;
44 ++I;
45 }
46 std::cerr << "\n";
47 std::cerr << "flags = " << action->flags << "\n";
48}
49
50void DumpConfigData(CompilerDriver::ConfigData* cd, const std::string& type ){
51 std::cerr << "Configuration Data For '" << cd->langName << "' (" << type
52 << ")\n";
53 std::cerr << "PreProcessor: ";
54 DumpAction(&cd->PreProcessor);
55 std::cerr << "Translator: ";
56 DumpAction(&cd->Translator);
57 std::cerr << "Optimizer: ";
58 DumpAction(&cd->Optimizer);
59 std::cerr << "Assembler: ";
60 DumpAction(&cd->Assembler);
61 std::cerr << "Linker: ";
62 DumpAction(&cd->Linker);
63}
64
65/// This specifies the passes to run for OPT_FAST_COMPILE (-O1)
66/// which should reduce the volume of code and make compilation
67/// faster. This is also safe on any llvm module.
68static const char* DefaultFastCompileOptimizations[] = {
69 "-simplifycfg", "-mem2reg", "-instcombine"
70};
71
72class CompilerDriverImpl : public CompilerDriver {
73/// @name Constructors
74/// @{
75public:
76 CompilerDriverImpl(ConfigDataProvider& confDatProv )
77 : cdp(&confDatProv)
78 , finalPhase(LINKING)
79 , optLevel(OPT_FAST_COMPILE)
80 , Flags(0)
81 , machine()
82 , LibraryPaths()
83 , TempDir()
84 , AdditionalArgs()
85 {
86 TempDir = sys::Path::GetTemporaryDirectory();
87 sys::RemoveDirectoryOnSignal(TempDir);
88 AdditionalArgs.reserve(NUM_PHASES);
89 StringVector emptyVec;
90 for (unsigned i = 0; i < NUM_PHASES; ++i)
91 AdditionalArgs.push_back(emptyVec);
92 }
93
94 virtual ~CompilerDriverImpl() {
95 cleanup();
96 cdp = 0;
97 LibraryPaths.clear();
98 IncludePaths.clear();
99 Defines.clear();
100 TempDir.clear();
101 AdditionalArgs.clear();
102 fOptions.clear();
103 MOptions.clear();
104 WOptions.clear();
105 }
106
107/// @}
108/// @name Methods
109/// @{
110public:
111 virtual void setFinalPhase( Phases phase ) {
112 finalPhase = phase;
113 }
114
115 virtual void setOptimization( OptimizationLevels level ) {
116 optLevel = level;
117 }
118
119 virtual void setDriverFlags( unsigned flags ) {
120 Flags = flags & DRIVER_FLAGS_MASK;
121 }
122
123 virtual void setOutputMachine( const std::string& machineName ) {
124 machine = machineName;
125 }
126
127 virtual void setPhaseArgs(Phases phase, const StringVector& opts) {
128 assert(phase <= LINKING && phase >= PREPROCESSING);
129 AdditionalArgs[phase] = opts;
130 }
131
132 virtual void setIncludePaths(const StringVector& paths) {
133 StringVector::const_iterator I = paths.begin();
134 StringVector::const_iterator E = paths.end();
135 while (I != E) {
136 sys::Path tmp;
Reid Spencer07adb282004-11-05 22:15:36 +0000137 tmp.setDirectory(*I);
Reid Spenceraf77d742004-10-28 04:05:06 +0000138 IncludePaths.push_back(tmp);
Reid Spencer68fb37a2004-08-14 09:37:15 +0000139 ++I;
140 }
Reid Spencer68fb37a2004-08-14 09:37:15 +0000141 }
142
Reid Spenceraf77d742004-10-28 04:05:06 +0000143 virtual void setSymbolDefines(const StringVector& defs) {
144 Defines = defs;
145 }
146
147 virtual void setLibraryPaths(const StringVector& paths) {
148 StringVector::const_iterator I = paths.begin();
149 StringVector::const_iterator E = paths.end();
150 while (I != E) {
151 sys::Path tmp;
Reid Spencer07adb282004-11-05 22:15:36 +0000152 tmp.setDirectory(*I);
Reid Spenceraf77d742004-10-28 04:05:06 +0000153 LibraryPaths.push_back(tmp);
Reid Spencerbf437722004-08-15 08:19:46 +0000154 ++I;
155 }
Reid Spencerbf437722004-08-15 08:19:46 +0000156 }
157
Reid Spenceraf77d742004-10-28 04:05:06 +0000158 virtual void addLibraryPath( const sys::Path& libPath ) {
159 LibraryPaths.push_back(libPath);
Reid Spencer68fb37a2004-08-14 09:37:15 +0000160 }
Reid Spencer5c56dc12004-08-13 20:22:43 +0000161
Reid Spencer07adb282004-11-05 22:15:36 +0000162 virtual void addToolPath( const sys::Path& toolPath ) {
163 ToolPaths.push_back(toolPath);
164 }
165
Reid Spenceraf77d742004-10-28 04:05:06 +0000166 virtual void setfPassThrough(const StringVector& fOpts) {
167 fOptions = fOpts;
168 }
Reid Spencer5c56dc12004-08-13 20:22:43 +0000169
Reid Spenceraf77d742004-10-28 04:05:06 +0000170 /// @brief Set the list of -M options to be passed through
171 virtual void setMPassThrough(const StringVector& MOpts) {
172 MOptions = MOpts;
173 }
Reid Spencerbae68252004-08-19 04:49:47 +0000174
Reid Spenceraf77d742004-10-28 04:05:06 +0000175 /// @brief Set the list of -W options to be passed through
176 virtual void setWPassThrough(const StringVector& WOpts) {
177 WOptions = WOpts;
178 }
179/// @}
180/// @name Functions
181/// @{
182private:
183 bool isSet(DriverFlags flag) {
184 return 0 != ((flag & DRIVER_FLAGS_MASK) & Flags);
185 }
Reid Spencerbae68252004-08-19 04:49:47 +0000186
Reid Spenceraf77d742004-10-28 04:05:06 +0000187 void cleanup() {
188 if (!isSet(KEEP_TEMPS_FLAG)) {
Reid Spencer07adb282004-11-05 22:15:36 +0000189 if (TempDir.isDirectory() && TempDir.writable())
190 TempDir.destroyDirectory(/*remove_contents=*/true);
Reid Spenceraf77d742004-10-28 04:05:06 +0000191 } else {
192 std::cout << "Temporary files are in " << TempDir.get() << "\n";
193 }
194 }
Reid Spencer52c2dc12004-08-29 19:26:56 +0000195
Reid Spenceraf77d742004-10-28 04:05:06 +0000196 sys::Path MakeTempFile(const std::string& basename,
197 const std::string& suffix ) {
198 sys::Path result(TempDir);
Reid Spencer07adb282004-11-05 22:15:36 +0000199 if (!result.appendFile(basename))
Reid Spenceraf77d742004-10-28 04:05:06 +0000200 throw basename + ": can't use this file name";
Reid Spencer07adb282004-11-05 22:15:36 +0000201 if (!result.appendSuffix(suffix))
Reid Spenceraf77d742004-10-28 04:05:06 +0000202 throw suffix + ": can't use this file suffix";
203 return result;
204 }
Reid Spencer52c2dc12004-08-29 19:26:56 +0000205
Reid Spenceraf77d742004-10-28 04:05:06 +0000206 Action* GetAction(ConfigData* cd,
207 const sys::Path& input,
208 const sys::Path& output,
209 Phases phase)
210 {
211 Action* pat = 0; ///< The pattern/template for the action
212 Action* action = new Action; ///< The actual action to execute
Reid Spencer52c2dc12004-08-29 19:26:56 +0000213
Reid Spenceraf77d742004-10-28 04:05:06 +0000214 // Get the action pattern
215 switch (phase) {
216 case PREPROCESSING: pat = &cd->PreProcessor; break;
217 case TRANSLATION: pat = &cd->Translator; break;
218 case OPTIMIZATION: pat = &cd->Optimizer; break;
219 case ASSEMBLY: pat = &cd->Assembler; break;
220 case LINKING: pat = &cd->Linker; break;
221 default:
222 assert(!"Invalid driver phase!");
223 break;
224 }
225 assert(pat != 0 && "Invalid command pattern");
Reid Spencer52c2dc12004-08-29 19:26:56 +0000226
Reid Spenceraf77d742004-10-28 04:05:06 +0000227 // Copy over some pattern things that don't need to change
228 action->program = pat->program;
229 action->flags = pat->flags;
Reid Spencer52c2dc12004-08-29 19:26:56 +0000230
Reid Spenceraf77d742004-10-28 04:05:06 +0000231 // Do the substitutions from the pattern to the actual
232 StringVector::iterator PI = pat->args.begin();
233 StringVector::iterator PE = pat->args.end();
234 while (PI != PE) {
235 if ((*PI)[0] == '%' && PI->length() >2) {
236 bool found = true;
237 switch ((*PI)[1]) {
238 case 'a':
239 if (*PI == "%args%") {
240 if (AdditionalArgs.size() > unsigned(phase))
241 if (!AdditionalArgs[phase].empty()) {
242 // Get specific options for each kind of action type
243 StringVector& addargs = AdditionalArgs[phase];
244 // Add specific options for each kind of action type
245 action->args.insert(action->args.end(), addargs.begin(),
246 addargs.end());
247 }
248 } else
249 found = false;
250 break;
251 case 'd':
252 if (*PI == "%defs%") {
253 StringVector::iterator I = Defines.begin();
254 StringVector::iterator E = Defines.end();
255 while (I != E) {
256 action->args.push_back( std::string("-D") + *I);
257 ++I;
258 }
259 } else
260 found = false;
261 break;
262 case 'f':
263 if (*PI == "%fOpts%") {
264 action->args.insert(action->args.end(), fOptions.begin(),
265 fOptions.end());
266 } else
267 found = false;
268 break;
269 case 'i':
270 if (*PI == "%in%") {
271 action->args.push_back(input.get());
272 } else if (*PI == "%incls%") {
273 PathVector::iterator I = IncludePaths.begin();
274 PathVector::iterator E = IncludePaths.end();
275 while (I != E) {
276 action->args.push_back( std::string("-I") + I->get() );
277 ++I;
278 }
279 } else
280 found = false;
281 break;
282 case 'l':
283 if (*PI == "%libs%") {
284 PathVector::iterator I = LibraryPaths.begin();
285 PathVector::iterator E = LibraryPaths.end();
286 while (I != E) {
287 action->args.push_back( std::string("-L") + I->get() );
288 ++I;
289 }
290 } else
291 found = false;
292 break;
293 case 'o':
294 if (*PI == "%out%") {
295 action->args.push_back(output.get());
296 } else if (*PI == "%opt%") {
297 if (!isSet(EMIT_RAW_FLAG)) {
298 if (cd->opts.size() > static_cast<unsigned>(optLevel) &&
299 !cd->opts[optLevel].empty())
300 action->args.insert(action->args.end(),
301 cd->opts[optLevel].begin(),
302 cd->opts[optLevel].end());
303 else
304 throw std::string("Optimization options for level ") +
305 utostr(unsigned(optLevel)) + " were not specified";
306 }
307 } else
308 found = false;
309 break;
310 case 's':
311 if (*PI == "%stats%") {
312 if (isSet(SHOW_STATS_FLAG))
313 action->args.push_back("-stats");
314 } else
315 found = false;
316 break;
317 case 't':
318 if (*PI == "%target%") {
319 action->args.push_back(std::string("-march=") + machine);
320 } else if (*PI == "%time%") {
321 if (isSet(TIME_PASSES_FLAG))
322 action->args.push_back("-time-passes");
323 } else
324 found = false;
325 break;
326 case 'v':
327 if (*PI == "%verbose%") {
328 if (isSet(VERBOSE_FLAG))
329 action->args.push_back("-v");
330 } else
331 found = false;
332 break;
333 case 'M':
334 if (*PI == "%Mopts") {
335 action->args.insert(action->args.end(), MOptions.begin(),
336 MOptions.end());
337 } else
338 found = false;
339 break;
340 case 'W':
341 if (*PI == "%Wopts") {
342 action->args.insert(action->args.end(), WOptions.begin(),
343 WOptions.end());
344 } else
345 found = false;
346 break;
Reid Spencer52c2dc12004-08-29 19:26:56 +0000347 default:
Reid Spenceraf77d742004-10-28 04:05:06 +0000348 found = false;
Reid Spencer52c2dc12004-08-29 19:26:56 +0000349 break;
350 }
Reid Spenceraf77d742004-10-28 04:05:06 +0000351 if (!found) {
352 // Did it even look like a substitution?
353 if (PI->length()>1 && (*PI)[0] == '%' &&
354 (*PI)[PI->length()-1] == '%') {
355 throw std::string("Invalid substitution token: '") + *PI +
356 "' for command '" + pat->program.get() + "'";
Reid Spencer52c2dc12004-08-29 19:26:56 +0000357 } else {
Reid Spenceraf77d742004-10-28 04:05:06 +0000358 // It's not a legal substitution, just pass it through
Reid Spencer52c2dc12004-08-29 19:26:56 +0000359 action->args.push_back(*PI);
360 }
Reid Spencer52c2dc12004-08-29 19:26:56 +0000361 }
Reid Spenceraf77d742004-10-28 04:05:06 +0000362 } else {
363 // Its not a substitution, just put it in the action
364 action->args.push_back(*PI);
Reid Spencer52c2dc12004-08-29 19:26:56 +0000365 }
Reid Spenceraf77d742004-10-28 04:05:06 +0000366 PI++;
367 }
Reid Spencer52c2dc12004-08-29 19:26:56 +0000368
Reid Spenceraf77d742004-10-28 04:05:06 +0000369 // Finally, we're done
370 return action;
371 }
Reid Spencer52c2dc12004-08-29 19:26:56 +0000372
Reid Spenceraf77d742004-10-28 04:05:06 +0000373 bool DoAction(Action*action) {
374 assert(action != 0 && "Invalid Action!");
375 if (isSet(VERBOSE_FLAG))
376 WriteAction(action);
377 if (!isSet(DRY_RUN_FLAG)) {
378 sys::Path progpath = sys::Program::FindProgramByName(
379 action->program.get());
Reid Spencer07adb282004-11-05 22:15:36 +0000380 if (progpath.isEmpty())
Reid Spenceraf77d742004-10-28 04:05:06 +0000381 throw std::string("Can't find program '"+progpath.get()+"'");
382 else if (progpath.executable())
383 action->program = progpath;
384 else
385 throw std::string("Program '"+progpath.get()+"' is not executable.");
386
387 // Invoke the program
388 if (isSet(TIME_ACTIONS_FLAG)) {
389 Timer timer(action->program.get());
390 timer.startTimer();
391 int resultCode =
392 sys::Program::ExecuteAndWait(action->program,action->args);
393 timer.stopTimer();
394 timer.print(timer,std::cerr);
395 return resultCode == 0;
Reid Spencer52c2dc12004-08-29 19:26:56 +0000396 }
Reid Spenceraf77d742004-10-28 04:05:06 +0000397 else
398 return 0 ==
399 sys::Program::ExecuteAndWait(action->program, action->args);
400 }
401 return true;
402 }
Reid Spencer52c2dc12004-08-29 19:26:56 +0000403
Reid Spenceraf77d742004-10-28 04:05:06 +0000404 /// This method tries various variants of a linkage item's file
405 /// name to see if it can find an appropriate file to link with
406 /// in the directory specified.
407 llvm::sys::Path GetPathForLinkageItem(const std::string& link_item,
408 const sys::Path& dir,
409 bool native = false) {
410 sys::Path fullpath(dir);
Reid Spencer07adb282004-11-05 22:15:36 +0000411 fullpath.appendFile(link_item);
Reid Spenceraf77d742004-10-28 04:05:06 +0000412 if (native) {
Reid Spencer07adb282004-11-05 22:15:36 +0000413 fullpath.appendSuffix("a");
Reid Spenceraf77d742004-10-28 04:05:06 +0000414 } else {
Reid Spencer07adb282004-11-05 22:15:36 +0000415 fullpath.appendSuffix("bc");
Reid Spenceraf77d742004-10-28 04:05:06 +0000416 if (fullpath.readable())
Reid Spencer52c2dc12004-08-29 19:26:56 +0000417 return fullpath;
Reid Spencer07adb282004-11-05 22:15:36 +0000418 fullpath.elideSuffix();
419 fullpath.appendSuffix("o");
Reid Spenceraf77d742004-10-28 04:05:06 +0000420 if (fullpath.readable())
421 return fullpath;
422 fullpath = dir;
Reid Spencer07adb282004-11-05 22:15:36 +0000423 fullpath.appendFile(std::string("lib") + link_item);
424 fullpath.appendSuffix("a");
Reid Spenceraf77d742004-10-28 04:05:06 +0000425 if (fullpath.readable())
426 return fullpath;
Reid Spencer07adb282004-11-05 22:15:36 +0000427 fullpath.elideSuffix();
428 fullpath.appendSuffix("so");
Reid Spenceraf77d742004-10-28 04:05:06 +0000429 if (fullpath.readable())
430 return fullpath;
431 }
432
433 // Didn't find one.
434 fullpath.clear();
435 return fullpath;
436 }
437
438 /// This method processes a linkage item. The item could be a
439 /// Bytecode file needing translation to native code and that is
440 /// dependent on other bytecode libraries, or a native code
441 /// library that should just be linked into the program.
442 bool ProcessLinkageItem(const llvm::sys::Path& link_item,
443 SetVector<sys::Path>& set,
444 std::string& err) {
445 // First, see if the unadorned file name is not readable. If so,
446 // we must track down the file in the lib search path.
447 sys::Path fullpath;
448 if (!link_item.readable()) {
449 // First, look for the library using the -L arguments specified
450 // on the command line.
451 PathVector::iterator PI = LibraryPaths.begin();
452 PathVector::iterator PE = LibraryPaths.end();
Reid Spencer07adb282004-11-05 22:15:36 +0000453 while (PI != PE && fullpath.isEmpty()) {
Reid Spenceraf77d742004-10-28 04:05:06 +0000454 fullpath = GetPathForLinkageItem(link_item.get(),*PI);
455 ++PI;
Reid Spencer52c2dc12004-08-29 19:26:56 +0000456 }
457
Reid Spenceraf77d742004-10-28 04:05:06 +0000458 // If we didn't find the file in any of the library search paths
459 // so we have to bail. No where else to look.
Reid Spencer07adb282004-11-05 22:15:36 +0000460 if (fullpath.isEmpty()) {
Reid Spenceraf77d742004-10-28 04:05:06 +0000461 err =
462 std::string("Can't find linkage item '") + link_item.get() + "'";
463 return false;
464 }
465 } else {
466 fullpath = link_item;
467 }
Reid Spencer52c2dc12004-08-29 19:26:56 +0000468
Reid Spenceraf77d742004-10-28 04:05:06 +0000469 // If we got here fullpath is the path to the file, and its readable.
470 set.insert(fullpath);
Reid Spencer52c2dc12004-08-29 19:26:56 +0000471
Reid Spenceraf77d742004-10-28 04:05:06 +0000472 // If its an LLVM bytecode file ...
Reid Spencer07adb282004-11-05 22:15:36 +0000473 if (fullpath.isBytecodeFile()) {
Reid Spenceraf77d742004-10-28 04:05:06 +0000474 // Process the dependent libraries recursively
475 Module::LibraryListType modlibs;
476 if (GetBytecodeDependentLibraries(fullpath.get(),modlibs)) {
477 // Traverse the dependent libraries list
478 Module::lib_iterator LI = modlibs.begin();
479 Module::lib_iterator LE = modlibs.end();
480 while ( LI != LE ) {
481 if (!ProcessLinkageItem(sys::Path(*LI),set,err)) {
482 if (err.empty()) {
483 err = std::string("Library '") + *LI +
484 "' is not valid for linking but is required by file '" +
485 fullpath.get() + "'";
486 } else {
487 err += " which is required by file '" + fullpath.get() + "'";
Reid Spencer52c2dc12004-08-29 19:26:56 +0000488 }
Reid Spencer52c2dc12004-08-29 19:26:56 +0000489 return false;
490 }
Reid Spenceraf77d742004-10-28 04:05:06 +0000491 ++LI;
Reid Spencer52c2dc12004-08-29 19:26:56 +0000492 }
Reid Spenceraf77d742004-10-28 04:05:06 +0000493 } else if (err.empty()) {
494 err = std::string(
495 "The dependent libraries could not be extracted from '") +
496 fullpath.get();
497 return false;
498 }
499 }
500 return true;
501 }
502
503/// @}
504/// @name Methods
505/// @{
506public:
507 virtual int execute(const InputList& InpList, const sys::Path& Output ) {
508 try {
509 // Echo the configuration of options if we're running verbose
510 if (isSet(DEBUG_FLAG)) {
511 std::cerr << "Compiler Driver Options:\n";
512 std::cerr << "DryRun = " << isSet(DRY_RUN_FLAG) << "\n";
513 std::cerr << "Verbose = " << isSet(VERBOSE_FLAG) << " \n";
514 std::cerr << "TimeActions = " << isSet(TIME_ACTIONS_FLAG) << "\n";
515 std::cerr << "TimePasses = " << isSet(TIME_PASSES_FLAG) << "\n";
516 std::cerr << "ShowStats = " << isSet(SHOW_STATS_FLAG) << "\n";
517 std::cerr << "EmitRawCode = " << isSet(EMIT_RAW_FLAG) << "\n";
518 std::cerr << "EmitNativeCode = " << isSet(EMIT_NATIVE_FLAG) << "\n";
519 std::cerr << "KeepTemps = " << isSet(KEEP_TEMPS_FLAG) << "\n";
520 std::cerr << "OutputMachine = " << machine << "\n";
521 InputList::const_iterator I = InpList.begin();
522 while ( I != InpList.end() ) {
523 std::cerr << "Input: " << I->first.get() << "(" << I->second
524 << ")\n";
525 ++I;
526 }
527 std::cerr << "Output: " << Output.get() << "\n";
Reid Spencer52c2dc12004-08-29 19:26:56 +0000528 }
529
Reid Spenceraf77d742004-10-28 04:05:06 +0000530 // If there's no input, we're done.
531 if (InpList.empty())
532 throw std::string("Nothing to compile.");
Reid Spencer52c2dc12004-08-29 19:26:56 +0000533
Reid Spenceraf77d742004-10-28 04:05:06 +0000534 // If they are asking for linking and didn't provide an output
535 // file then its an error (no way for us to "make up" a meaningful
536 // file name based on the various linker input files).
Reid Spencer07adb282004-11-05 22:15:36 +0000537 if (finalPhase == LINKING && Output.isEmpty())
Reid Spenceraf77d742004-10-28 04:05:06 +0000538 throw std::string(
539 "An output file name must be specified for linker output");
Reid Spencer52c2dc12004-08-29 19:26:56 +0000540
Reid Spenceraf77d742004-10-28 04:05:06 +0000541 // If they are not asking for linking, provided an output file and
542 // there is more than one input file, its an error
Reid Spencer07adb282004-11-05 22:15:36 +0000543 if (finalPhase != LINKING && !Output.isEmpty() && InpList.size() > 1)
Reid Spenceraf77d742004-10-28 04:05:06 +0000544 throw std::string("An output file name cannot be specified ") +
545 "with more than one input file name when not linking";
546
547 // This vector holds all the resulting actions of the following loop.
548 std::vector<Action*> actions;
549
550 /// PRE-PROCESSING / TRANSLATION / OPTIMIZATION / ASSEMBLY phases
551 // for each input item
552 SetVector<sys::Path> LinkageItems;
553 std::vector<std::string> LibFiles;
554 InputList::const_iterator I = InpList.begin();
555 while ( I != InpList.end() ) {
556 // Get the suffix of the file name
557 const std::string& ftype = I->second;
558
559 // If its a library, bytecode file, or object file, save
560 // it for linking below and short circuit the
561 // pre-processing/translation/assembly phases
562 if (ftype.empty() || ftype == "o" || ftype == "bc" || ftype=="a") {
563 // We shouldn't get any of these types of files unless we're
564 // later going to link. Enforce this limit now.
565 if (finalPhase != LINKING) {
Reid Spencer52c2dc12004-08-29 19:26:56 +0000566 throw std::string(
Reid Spenceraf77d742004-10-28 04:05:06 +0000567 "Pre-compiled objects found but linking not requested");
568 }
569 if (ftype.empty())
570 LibFiles.push_back(I->first.get());
571 else
572 LinkageItems.insert(I->first);
573 ++I; continue; // short circuit remainder of loop
574 }
Reid Spencer52c2dc12004-08-29 19:26:56 +0000575
Reid Spenceraf77d742004-10-28 04:05:06 +0000576 // At this point, we know its something we need to translate
577 // and/or optimize. See if we can get the configuration data
578 // for this kind of file.
579 ConfigData* cd = cdp->ProvideConfigData(I->second);
580 if (cd == 0)
581 throw std::string("Files of type '") + I->second +
582 "' are not recognized.";
583 if (isSet(DEBUG_FLAG))
584 DumpConfigData(cd,I->second);
Reid Spencer54fafe42004-09-14 01:58:45 +0000585
Reid Spenceraf77d742004-10-28 04:05:06 +0000586 // Initialize the input and output files
587 sys::Path InFile(I->first);
Reid Spencer07adb282004-11-05 22:15:36 +0000588 sys::Path OutFile(I->first.getBasename());
Reid Spencer52c2dc12004-08-29 19:26:56 +0000589
Reid Spenceraf77d742004-10-28 04:05:06 +0000590 // PRE-PROCESSING PHASE
591 Action& action = cd->PreProcessor;
Reid Spencer52c2dc12004-08-29 19:26:56 +0000592
Reid Spenceraf77d742004-10-28 04:05:06 +0000593 // Get the preprocessing action, if needed, or error if appropriate
Reid Spencer07adb282004-11-05 22:15:36 +0000594 if (!action.program.isEmpty()) {
Reid Spenceraf77d742004-10-28 04:05:06 +0000595 if (action.isSet(REQUIRED_FLAG) || finalPhase == PREPROCESSING) {
596 if (finalPhase == PREPROCESSING) {
Reid Spencer07adb282004-11-05 22:15:36 +0000597 OutFile.appendSuffix("E");
Reid Spenceraf77d742004-10-28 04:05:06 +0000598 actions.push_back(GetAction(cd,InFile,OutFile,PREPROCESSING));
599 } else {
Reid Spencer07adb282004-11-05 22:15:36 +0000600 sys::Path TempFile(MakeTempFile(I->first.getBasename(),"E"));
Reid Spenceraf77d742004-10-28 04:05:06 +0000601 actions.push_back(GetAction(cd,InFile,TempFile,
602 PREPROCESSING));
603 InFile = TempFile;
604 }
605 }
606 } else if (finalPhase == PREPROCESSING) {
607 throw cd->langName + " does not support pre-processing";
608 } else if (action.isSet(REQUIRED_FLAG)) {
609 throw std::string("Don't know how to pre-process ") +
610 cd->langName + " files";
611 }
612
613 // Short-circuit remaining actions if all they want is
614 // pre-processing
615 if (finalPhase == PREPROCESSING) { ++I; continue; };
616
617 /// TRANSLATION PHASE
618 action = cd->Translator;
619
620 // Get the translation action, if needed, or error if appropriate
Reid Spencer07adb282004-11-05 22:15:36 +0000621 if (!action.program.isEmpty()) {
Reid Spenceraf77d742004-10-28 04:05:06 +0000622 if (action.isSet(REQUIRED_FLAG) || finalPhase == TRANSLATION) {
623 if (finalPhase == TRANSLATION) {
Reid Spencer07adb282004-11-05 22:15:36 +0000624 OutFile.appendSuffix("o");
Reid Spenceraf77d742004-10-28 04:05:06 +0000625 actions.push_back(GetAction(cd,InFile,OutFile,TRANSLATION));
626 } else {
Reid Spencer07adb282004-11-05 22:15:36 +0000627 sys::Path TempFile(MakeTempFile(I->first.getBasename(),"trans"));
Reid Spenceraf77d742004-10-28 04:05:06 +0000628 actions.push_back(GetAction(cd,InFile,TempFile,TRANSLATION));
629 InFile = TempFile;
Reid Spencer52c2dc12004-08-29 19:26:56 +0000630 }
631
Reid Spenceraf77d742004-10-28 04:05:06 +0000632 // ll -> bc Helper
633 if (action.isSet(OUTPUT_IS_ASM_FLAG)) {
634 /// The output of the translator is an LLVM Assembly program
635 /// We need to translate it to bytecode
636 Action* action = new Action();
Reid Spencer07adb282004-11-05 22:15:36 +0000637 action->program.setFile("llvm-as");
Reid Spenceraf77d742004-10-28 04:05:06 +0000638 action->args.push_back(InFile.get());
639 action->args.push_back("-o");
Reid Spencer07adb282004-11-05 22:15:36 +0000640 InFile.appendSuffix("bc");
Reid Spenceraf77d742004-10-28 04:05:06 +0000641 action->args.push_back(InFile.get());
642 actions.push_back(action);
Reid Spencer52c2dc12004-08-29 19:26:56 +0000643 }
Reid Spenceraf77d742004-10-28 04:05:06 +0000644 }
645 } else if (finalPhase == TRANSLATION) {
646 throw cd->langName + " does not support translation";
647 } else if (action.isSet(REQUIRED_FLAG)) {
648 throw std::string("Don't know how to translate ") +
649 cd->langName + " files";
650 }
Reid Spencer52c2dc12004-08-29 19:26:56 +0000651
Reid Spenceraf77d742004-10-28 04:05:06 +0000652 // Short-circuit remaining actions if all they want is translation
653 if (finalPhase == TRANSLATION) { ++I; continue; }
Reid Spencer52c2dc12004-08-29 19:26:56 +0000654
Reid Spenceraf77d742004-10-28 04:05:06 +0000655 /// OPTIMIZATION PHASE
656 action = cd->Optimizer;
Reid Spencer52c2dc12004-08-29 19:26:56 +0000657
Reid Spenceraf77d742004-10-28 04:05:06 +0000658 // Get the optimization action, if needed, or error if appropriate
659 if (!isSet(EMIT_RAW_FLAG)) {
Reid Spencer07adb282004-11-05 22:15:36 +0000660 if (!action.program.isEmpty()) {
Reid Spenceraf77d742004-10-28 04:05:06 +0000661 if (action.isSet(REQUIRED_FLAG) || finalPhase == OPTIMIZATION) {
662 if (finalPhase == OPTIMIZATION) {
Reid Spencer07adb282004-11-05 22:15:36 +0000663 OutFile.appendSuffix("o");
Reid Spenceraf77d742004-10-28 04:05:06 +0000664 actions.push_back(GetAction(cd,InFile,OutFile,OPTIMIZATION));
Reid Spencer52c2dc12004-08-29 19:26:56 +0000665 } else {
Reid Spencer07adb282004-11-05 22:15:36 +0000666 sys::Path TempFile(MakeTempFile(I->first.getBasename(),"opt"));
Reid Spenceraf77d742004-10-28 04:05:06 +0000667 actions.push_back(GetAction(cd,InFile,TempFile,OPTIMIZATION));
668 InFile = TempFile;
669 }
670 // ll -> bc Helper
671 if (action.isSet(OUTPUT_IS_ASM_FLAG)) {
672 /// The output of the optimizer is an LLVM Assembly program
673 /// We need to translate it to bytecode with llvm-as
Reid Spencer52c2dc12004-08-29 19:26:56 +0000674 Action* action = new Action();
Reid Spencer07adb282004-11-05 22:15:36 +0000675 action->program.setFile("llvm-as");
Reid Spencer52c2dc12004-08-29 19:26:56 +0000676 action->args.push_back(InFile.get());
677 action->args.push_back("-f");
678 action->args.push_back("-o");
Reid Spencer07adb282004-11-05 22:15:36 +0000679 InFile.appendSuffix("bc");
Reid Spenceraf77d742004-10-28 04:05:06 +0000680 action->args.push_back(InFile.get());
Reid Spencer52c2dc12004-08-29 19:26:56 +0000681 actions.push_back(action);
682 }
683 }
Reid Spenceraf77d742004-10-28 04:05:06 +0000684 } else if (finalPhase == OPTIMIZATION) {
685 throw cd->langName + " does not support optimization";
686 } else if (action.isSet(REQUIRED_FLAG)) {
687 throw std::string("Don't know how to optimize ") +
688 cd->langName + " files";
Reid Spencer52c2dc12004-08-29 19:26:56 +0000689 }
Reid Spencer52c2dc12004-08-29 19:26:56 +0000690 }
Reid Spenceraf77d742004-10-28 04:05:06 +0000691
692 // Short-circuit remaining actions if all they want is optimization
693 if (finalPhase == OPTIMIZATION) { ++I; continue; }
694
695 /// ASSEMBLY PHASE
696 action = cd->Assembler;
697
698 if (finalPhase == ASSEMBLY) {
699 if (isSet(EMIT_NATIVE_FLAG)) {
700 // Use llc to get the native assembly file
701 Action* action = new Action();
Reid Spencer07adb282004-11-05 22:15:36 +0000702 action->program.setFile("llc");
Reid Spenceraf77d742004-10-28 04:05:06 +0000703 action->args.push_back(InFile.get());
704 action->args.push_back("-f");
705 action->args.push_back("-o");
Reid Spencer07adb282004-11-05 22:15:36 +0000706 OutFile.appendSuffix("s");
Reid Spenceraf77d742004-10-28 04:05:06 +0000707 action->args.push_back(OutFile.get());
708 } else {
709 // Just convert back to llvm assembly with llvm-dis
710 Action* action = new Action();
Reid Spencer07adb282004-11-05 22:15:36 +0000711 action->program.setFile("llvm-dis");
Reid Spenceraf77d742004-10-28 04:05:06 +0000712 action->args.push_back(InFile.get());
713 action->args.push_back("-f");
714 action->args.push_back("-o");
Reid Spencer07adb282004-11-05 22:15:36 +0000715 OutFile.appendSuffix("ll");
Reid Spenceraf77d742004-10-28 04:05:06 +0000716 action->args.push_back(OutFile.get());
717 actions.push_back(action);
718 }
719
720 // Short circuit the rest of the loop, we don't want to link
721 ++I;
722 continue;
723 }
724
725 // Register the result of the actions as a link candidate
726 LinkageItems.insert(InFile);
727
728 // Go to next file to be processed
729 ++I;
730 } // end while loop over each input file
731
732 /// RUN THE COMPILATION ACTIONS
733 std::vector<Action*>::iterator AI = actions.begin();
734 std::vector<Action*>::iterator AE = actions.end();
735 while (AI != AE) {
736 if (!DoAction(*AI))
737 throw std::string("Action failed");
738 AI++;
Reid Spencer52c2dc12004-08-29 19:26:56 +0000739 }
740
Reid Spenceraf77d742004-10-28 04:05:06 +0000741 /// LINKING PHASE
742 if (finalPhase == LINKING) {
Reid Spencer52c2dc12004-08-29 19:26:56 +0000743
Reid Spenceraf77d742004-10-28 04:05:06 +0000744 // Insert the platform-specific system libraries to the path list
745 LibraryPaths.push_back(sys::Path::GetSystemLibraryPath1());
746 LibraryPaths.push_back(sys::Path::GetSystemLibraryPath2());
747
748 // Set up the linking action with llvm-ld
749 Action* link = new Action();
Reid Spencer07adb282004-11-05 22:15:36 +0000750 link->program.setFile("llvm-ld");
Reid Spenceraf77d742004-10-28 04:05:06 +0000751
752 // Add in the optimization level requested
753 switch (optLevel) {
754 case OPT_FAST_COMPILE:
755 link->args.push_back("-O1");
756 break;
757 case OPT_SIMPLE:
758 link->args.push_back("-O2");
759 break;
760 case OPT_AGGRESSIVE:
761 link->args.push_back("-O3");
762 break;
763 case OPT_LINK_TIME:
764 link->args.push_back("-O4");
765 break;
766 case OPT_AGGRESSIVE_LINK_TIME:
767 link->args.push_back("-O5");
768 break;
769 case OPT_NONE:
770 break;
771 }
772
773 // Add in all the linkage items we generated. This includes the
774 // output from the translation/optimization phases as well as any
775 // -l arguments specified.
776 for (PathVector::const_iterator I=LinkageItems.begin(),
777 E=LinkageItems.end(); I != E; ++I )
778 link->args.push_back(I->get());
779
780 // Add in all the libraries we found.
781 for (std::vector<std::string>::const_iterator I=LibFiles.begin(),
782 E=LibFiles.end(); I != E; ++I )
783 link->args.push_back(std::string("-l")+*I);
784
785 // Add in all the library paths to the command line
786 for (PathVector::const_iterator I=LibraryPaths.begin(),
787 E=LibraryPaths.end(); I != E; ++I)
788 link->args.push_back( std::string("-L") + I->get());
789
790 // Add in the additional linker arguments requested
791 for (StringVector::const_iterator I=AdditionalArgs[LINKING].begin(),
792 E=AdditionalArgs[LINKING].end(); I != E; ++I)
793 link->args.push_back( *I );
794
795 // Add in other optional flags
796 if (isSet(EMIT_NATIVE_FLAG))
797 link->args.push_back("-native");
798 if (isSet(VERBOSE_FLAG))
799 link->args.push_back("-v");
800 if (isSet(TIME_PASSES_FLAG))
801 link->args.push_back("-time-passes");
802 if (isSet(SHOW_STATS_FLAG))
803 link->args.push_back("-stats");
804 if (isSet(STRIP_OUTPUT_FLAG))
805 link->args.push_back("-s");
806 if (isSet(DEBUG_FLAG)) {
807 link->args.push_back("-debug");
808 link->args.push_back("-debug-pass=Details");
809 }
810
811 // Add in mandatory flags
812 link->args.push_back("-o");
813 link->args.push_back(Output.get());
814
815 // Execute the link
816 if (!DoAction(link))
817 throw std::string("Action failed");
818 }
819 } catch (std::string& msg) {
820 cleanup();
821 throw;
822 } catch (...) {
823 cleanup();
824 throw std::string("Unspecified error");
825 }
826 cleanup();
827 return 0;
828 }
829
830/// @}
831/// @name Data
832/// @{
833private:
834 ConfigDataProvider* cdp; ///< Where we get configuration data from
835 Phases finalPhase; ///< The final phase of compilation
836 OptimizationLevels optLevel; ///< The optimization level to apply
837 unsigned Flags; ///< The driver flags
838 std::string machine; ///< Target machine name
839 PathVector LibraryPaths; ///< -L options
840 PathVector IncludePaths; ///< -I options
Reid Spencer07adb282004-11-05 22:15:36 +0000841 PathVector ToolPaths; ///< -B options
Reid Spenceraf77d742004-10-28 04:05:06 +0000842 StringVector Defines; ///< -D options
843 sys::Path TempDir; ///< Name of the temporary directory.
844 StringTable AdditionalArgs; ///< The -Txyz options
845 StringVector fOptions; ///< -f options
846 StringVector MOptions; ///< -M options
847 StringVector WOptions; ///< -W options
848
849/// @}
850};
Reid Spencer5c56dc12004-08-13 20:22:43 +0000851}
852
853CompilerDriver::~CompilerDriver() {
Reid Spencer52c2dc12004-08-29 19:26:56 +0000854}
855
856CompilerDriver*
857CompilerDriver::Get(ConfigDataProvider& CDP) {
858 return new CompilerDriverImpl(CDP);
Reid Spencerbae68252004-08-19 04:49:47 +0000859}
860
861CompilerDriver::ConfigData::ConfigData()
862 : langName()
863 , PreProcessor()
864 , Translator()
865 , Optimizer()
866 , Assembler()
867 , Linker()
868{
869 StringVector emptyVec;
870 for (unsigned i = 0; i < NUM_PHASES; ++i)
871 opts.push_back(emptyVec);
Reid Spencer5c56dc12004-08-13 20:22:43 +0000872}
873
Reid Spencer5c56dc12004-08-13 20:22:43 +0000874// vim: sw=2 smartindent smarttab tw=80 autoindent expandtab