1 //===- CompilerDriver.cpp - The LLVM Compiler Driver ------------*- C++ -*-===//
4 // The LLVM Compiler Infrastructure
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.
9 //===----------------------------------------------------------------------===//
11 // This file implements the bulk of the LLVM Compiler Driver (llvmc).
13 //===----------------------------------------------------------------------===//
15 #include "CompilerDriver.h"
16 #include "ConfigLexer.h"
17 #include "llvm/Module.h"
18 #include "llvm/ModuleProvider.h"
19 #include "llvm/Bitcode/ReaderWriter.h"
20 #include "llvm/Support/MemoryBuffer.h"
21 #include "llvm/Support/Timer.h"
22 #include "llvm/System/Signals.h"
23 #include "llvm/ADT/SetVector.h"
24 #include "llvm/ADT/StringExtras.h"
25 #include "llvm/Config/alloca.h"
32 void WriteAction(CompilerDriver::Action
* action
) {
33 std::cerr
<< action
->program
.c_str();
34 std::vector
<std::string
>::const_iterator I
= action
->args
.begin();
35 while (I
!= action
->args
.end()) {
36 std::cerr
<< ' ' << *I
;
42 void DumpAction(CompilerDriver::Action
* action
) {
43 std::cerr
<< "command = " << action
->program
.c_str();
44 std::vector
<std::string
>::const_iterator I
= action
->args
.begin();
45 while (I
!= action
->args
.end()) {
46 std::cerr
<< ' ' << *I
;
50 std::cerr
<< "flags = " << action
->flags
<< '\n';
53 void DumpConfigData(CompilerDriver::ConfigData
* cd
, const std::string
& type
){
54 std::cerr
<< "Configuration Data For '" << cd
->langName
<< "' (" << type
56 std::cerr
<< "PreProcessor: ";
57 DumpAction(&cd
->PreProcessor
);
58 std::cerr
<< "Translator: ";
59 DumpAction(&cd
->Translator
);
60 std::cerr
<< "Optimizer: ";
61 DumpAction(&cd
->Optimizer
);
62 std::cerr
<< "Assembler: ";
63 DumpAction(&cd
->Assembler
);
64 std::cerr
<< "Linker: ";
65 DumpAction(&cd
->Linker
);
68 static bool GetBitcodeDependentLibraries(const std::string
&fname
,
69 Module::LibraryListType
& deplibs
,
70 std::string
* ErrMsg
) {
71 ModuleProvider
*MP
= 0;
72 if (MemoryBuffer
*Buffer
= MemoryBuffer::getFileOrSTDIN(fname
)) {
73 MP
= getBitcodeModuleProvider(Buffer
);
74 if (MP
== 0) delete Buffer
;
80 deplibs
= MP
->getModule()->getLibraries();
86 class CompilerDriverImpl
: public CompilerDriver
{
87 /// @name Constructors
90 CompilerDriverImpl(ConfigDataProvider
& confDatProv
)
93 , optLevel(OPT_FAST_COMPILE
)
100 AdditionalArgs
.reserve(NUM_PHASES
);
101 StringVector emptyVec
;
102 for (unsigned i
= 0; i
< NUM_PHASES
; ++i
)
103 AdditionalArgs
.push_back(emptyVec
);
106 virtual ~CompilerDriverImpl() {
109 LibraryPaths
.clear();
110 IncludePaths
.clear();
113 AdditionalArgs
.clear();
123 virtual void setFinalPhase(Phases phase
) {
127 virtual void setOptimization(OptimizationLevels level
) {
131 virtual void setDriverFlags(unsigned flags
) {
132 Flags
= flags
& DRIVER_FLAGS_MASK
;
135 virtual void setOutputMachine(const std::string
& machineName
) {
136 machine
= machineName
;
139 virtual void setPhaseArgs(Phases phase
, const StringVector
& opts
) {
140 assert(phase
<= LINKING
&& phase
>= PREPROCESSING
);
141 AdditionalArgs
[phase
] = opts
;
144 virtual void setIncludePaths(const StringVector
& paths
) {
145 StringVector::const_iterator I
= paths
.begin();
146 StringVector::const_iterator E
= paths
.end();
150 IncludePaths
.push_back(tmp
);
155 virtual void setSymbolDefines(const StringVector
& defs
) {
159 virtual void setLibraryPaths(const StringVector
& paths
) {
160 StringVector::const_iterator I
= paths
.begin();
161 StringVector::const_iterator E
= paths
.end();
165 LibraryPaths
.push_back(tmp
);
170 virtual void addLibraryPath(const sys::Path
& libPath
) {
171 LibraryPaths
.push_back(libPath
);
174 virtual void addToolPath(const sys::Path
& toolPath
) {
175 ToolPaths
.push_back(toolPath
);
178 virtual void setfPassThrough(const StringVector
& fOpts
) {
182 /// @brief Set the list of -M options to be passed through
183 virtual void setMPassThrough(const StringVector
& MOpts
) {
187 /// @brief Set the list of -W options to be passed through
188 virtual void setWPassThrough(const StringVector
& WOpts
) {
196 bool isSet(DriverFlags flag
) {
197 return 0 != ((flag
& DRIVER_FLAGS_MASK
) & Flags
);
201 if (!isSet(KEEP_TEMPS_FLAG
)) {
202 const sys::FileStatus
*Status
= TempDir
.getFileStatus();
203 if (Status
&& Status
->isDir
)
204 TempDir
.eraseFromDisk(/*remove_contents=*/true);
206 std::cout
<< "Temporary files are in " << TempDir
<< "\n";
210 sys::Path
MakeTempFile(const std::string
& basename
,
211 const std::string
& suffix
,
212 std::string
* ErrMsg
) {
213 if (TempDir
.isEmpty()) {
214 TempDir
= sys::Path::GetTemporaryDirectory(ErrMsg
);
215 if (TempDir
.isEmpty())
217 sys::RemoveDirectoryOnSignal(TempDir
);
219 sys::Path
result(TempDir
);
220 if (!result
.appendComponent(basename
)) {
222 *ErrMsg
= basename
+ ": can't use this file name";
225 if (!result
.appendSuffix(suffix
)) {
227 *ErrMsg
= suffix
+ ": can't use this file suffix";
233 Action
* GetAction(ConfigData
* cd
,
234 const sys::Path
& input
,
235 const sys::Path
& output
,
238 Action
* pat
= 0; ///< The pattern/template for the action
239 Action
* action
= new Action
; ///< The actual action to execute
241 // Get the action pattern
243 case PREPROCESSING
: pat
= &cd
->PreProcessor
; break;
244 case TRANSLATION
: pat
= &cd
->Translator
; break;
245 case OPTIMIZATION
: pat
= &cd
->Optimizer
; break;
246 case ASSEMBLY
: pat
= &cd
->Assembler
; break;
247 case LINKING
: pat
= &cd
->Linker
; break;
249 assert(!"Invalid driver phase!");
252 assert(pat
!= 0 && "Invalid command pattern");
254 // Copy over some pattern things that don't need to change
255 action
->flags
= pat
->flags
;
257 // See if program starts with wildcard...
258 std::string programName
=pat
->program
.toString();
259 if (programName
[0] == '%' && programName
.length() >2) {
260 switch(programName
[1]){
262 if (programName
.substr(0,8) == "%bindir%") {
263 std::string
tmp(LLVM_BINDIR
);
264 tmp
.append(programName
.substr(8));
265 pat
->program
.set(tmp
);
269 if (programName
.substr(0,12) == "%llvmgccdir%"){
270 std::string
tmp(LLVMGCCDIR
);
271 tmp
.append(programName
.substr(12));
272 pat
->program
.set(tmp
);
273 }else if (programName
.substr(0,13) == "%llvmgccarch%"){
274 std::string
tmp(LLVMGCCARCH
);
275 tmp
.append(programName
.substr(13));
276 pat
->program
.set(tmp
);
277 }else if (programName
.substr(0,9) == "%llvmgcc%"){
278 std::string
tmp(LLVMGCC
);
279 tmp
.append(programName
.substr(9));
280 pat
->program
.set(tmp
);
281 }else if (programName
.substr(0,9) == "%llvmgxx%"){
282 std::string
tmp(LLVMGXX
);
283 tmp
.append(programName
.substr(9));
284 pat
->program
.set(tmp
);
285 }else if (programName
.substr(0,9) == "%llvmcc1%"){
286 std::string
tmp(LLVMCC1
);
287 tmp
.append(programName
.substr(9));
288 pat
->program
.set(tmp
);
289 }else if (programName
.substr(0,13) == "%llvmcc1plus%"){
290 std::string
tmp(LLVMCC1PLUS
);
291 tmp
.append(programName
.substr(13));
292 pat
->program
.set(tmp
);
293 }else if (programName
.substr(0,8) == "%libdir%") {
294 std::string
tmp(LLVM_LIBDIR
);
295 tmp
.append(programName
.substr(8));
296 pat
->program
.set(tmp
);
301 action
->program
= pat
->program
;
303 // Do the substitutions from the pattern to the actual
304 StringVector::iterator PI
= pat
->args
.begin();
305 StringVector::iterator PE
= pat
->args
.end();
307 if ((*PI
)[0] == '%' && PI
->length() >2) {
311 if (*PI
== "%args%") {
312 if (AdditionalArgs
.size() > unsigned(phase
))
313 if (!AdditionalArgs
[phase
].empty()) {
314 // Get specific options for each kind of action type
315 StringVector
& addargs
= AdditionalArgs
[phase
];
316 // Add specific options for each kind of action type
317 action
->args
.insert(action
->args
.end(), addargs
.begin(),
324 if (*PI
== "%bindir%") {
325 std::string
tmp(*PI
);
326 tmp
.replace(0,8,LLVM_BINDIR
);
327 action
->args
.push_back(tmp
);
332 if (*PI
== "%defs%") {
333 StringVector::iterator I
= Defines
.begin();
334 StringVector::iterator E
= Defines
.end();
336 action
->args
.push_back( std::string("-D") + *I
);
343 if (*PI
== "%fOpts%") {
344 if (!fOptions
.empty())
345 action
->args
.insert(action
->args
.end(), fOptions
.begin(),
352 action
->args
.push_back(input
.toString());
353 } else if (*PI
== "%incls%") {
354 PathVector::iterator I
= IncludePaths
.begin();
355 PathVector::iterator E
= IncludePaths
.end();
357 action
->args
.push_back( std::string("-I") + I
->toString() );
364 if ((*PI
)[1] == 'l') {
365 std::string
tmp(*PI
);
366 if (*PI
== "%llvmgccdir%")
367 tmp
.replace(0,12,LLVMGCCDIR
);
368 else if (*PI
== "%llvmgccarch%")
369 tmp
.replace(0,13,LLVMGCCARCH
);
370 else if (*PI
== "%llvmgcc%")
371 tmp
.replace(0,9,LLVMGCC
);
372 else if (*PI
== "%llvmgxx%")
373 tmp
.replace(0,9,LLVMGXX
);
374 else if (*PI
== "%llvmcc1%")
375 tmp
.replace(0,9,LLVMCC1
);
376 else if (*PI
== "%llvmcc1plus%")
377 tmp
.replace(0,9,LLVMCC1
);
381 action
->args
.push_back(tmp
);
382 } else if (*PI
== "%libs%") {
383 PathVector::iterator I
= LibraryPaths
.begin();
384 PathVector::iterator E
= LibraryPaths
.end();
386 action
->args
.push_back( std::string("-L") + I
->toString() );
389 } else if (*PI
== "%libdir%") {
390 std::string
tmp(*PI
);
391 tmp
.replace(0,8,LLVM_LIBDIR
);
392 action
->args
.push_back(tmp
);
397 if (*PI
== "%out%") {
398 action
->args
.push_back(output
.toString());
399 } else if (*PI
== "%opt%") {
400 if (!isSet(EMIT_RAW_FLAG
)) {
401 if (cd
->opts
.size() > static_cast<unsigned>(optLevel
) &&
402 !cd
->opts
[optLevel
].empty())
403 action
->args
.insert(action
->args
.end(),
404 cd
->opts
[optLevel
].begin(),
405 cd
->opts
[optLevel
].end());
407 throw std::string("Optimization options for level ") +
408 utostr(unsigned(optLevel
)) + " were not specified";
414 if (*PI
== "%stats%") {
415 if (isSet(SHOW_STATS_FLAG
))
416 action
->args
.push_back("-stats");
421 if (*PI
== "%target%") {
422 action
->args
.push_back(std::string("-march=") + machine
);
423 } else if (*PI
== "%time%") {
424 if (isSet(TIME_PASSES_FLAG
))
425 action
->args
.push_back("-time-passes");
430 if (*PI
== "%verbose%") {
431 if (isSet(VERBOSE_FLAG
))
432 action
->args
.push_back("-v");
437 if (*PI
== "%Mopts%") {
438 if (!MOptions
.empty())
439 action
->args
.insert(action
->args
.end(), MOptions
.begin(),
445 if (*PI
== "%Wopts%") {
446 for (StringVector::iterator I
= WOptions
.begin(),
447 E
= WOptions
.end(); I
!= E
; ++I
) {
448 action
->args
.push_back(std::string("-W") + *I
);
458 // Did it even look like a substitution?
459 if (PI
->length()>1 && (*PI
)[0] == '%' &&
460 (*PI
)[PI
->length()-1] == '%') {
461 throw std::string("Invalid substitution token: '") + *PI
+
462 "' for command '" + pat
->program
.toString() + "'";
463 } else if (!PI
->empty()) {
464 // It's not a legal substitution, just pass it through
465 action
->args
.push_back(*PI
);
468 } else if (!PI
->empty()) {
469 // Its not a substitution, just put it in the action
470 action
->args
.push_back(*PI
);
475 // Finally, we're done
479 int DoAction(Action
*action
, std::string
& ErrMsg
) {
480 assert(action
!= 0 && "Invalid Action!");
481 if (isSet(VERBOSE_FLAG
))
483 if (!isSet(DRY_RUN_FLAG
)) {
484 sys::Path progpath
= sys::Program::FindProgramByName(
485 action
->program
.toString());
486 if (progpath
.isEmpty())
487 throw std::string("Can't find program '" +
488 action
->program
.toString()+"'");
489 else if (progpath
.canExecute())
490 action
->program
= progpath
;
492 throw std::string("Program '"+action
->program
.toString()+
493 "' is not executable.");
495 // Invoke the program
496 const char** Args
= (const char**)
497 alloca(sizeof(const char*)*(action
->args
.size()+2));
498 Args
[0] = action
->program
.toString().c_str();
499 for (unsigned i
= 1; i
<= action
->args
.size(); ++i
)
500 Args
[i
] = action
->args
[i
-1].c_str();
501 Args
[action
->args
.size()+1] = 0; // null terminate list.
502 if (isSet(TIME_ACTIONS_FLAG
)) {
503 Timer
timer(action
->program
.toString());
506 sys::Program::ExecuteAndWait(action
->program
, Args
,0,0,0,0, &ErrMsg
);
508 timer
.print(timer
,std::cerr
);
513 sys::Program::ExecuteAndWait(action
->program
, Args
, 0,0,0,0, &ErrMsg
);
518 /// This method tries various variants of a linkage item's file
519 /// name to see if it can find an appropriate file to link with
520 /// in the directories of the LibraryPaths.
521 llvm::sys::Path
GetPathForLinkageItem(const std::string
& link_item
,
522 bool native
= false) {
524 fullpath
.set(link_item
);
525 if (fullpath
.canRead())
527 for (PathVector::iterator PI
= LibraryPaths
.begin(),
528 PE
= LibraryPaths
.end(); PI
!= PE
; ++PI
) {
529 fullpath
.set(PI
->toString());
530 fullpath
.appendComponent(link_item
);
531 if (fullpath
.canRead())
534 fullpath
.appendSuffix("a");
536 fullpath
.appendSuffix("bc");
537 if (fullpath
.canRead())
539 fullpath
.eraseSuffix();
540 fullpath
.appendSuffix("o");
541 if (fullpath
.canRead())
544 fullpath
.appendComponent(std::string("lib") + link_item
);
545 fullpath
.appendSuffix("a");
546 if (fullpath
.canRead())
548 fullpath
.eraseSuffix();
549 fullpath
.appendSuffix("so");
550 if (fullpath
.canRead())
560 /// This method processes a linkage item. The item could be a
561 /// Bitcode file needing translation to native code and that is
562 /// dependent on other bitcode libraries, or a native code
563 /// library that should just be linked into the program.
564 bool ProcessLinkageItem(const llvm::sys::Path
& link_item
,
565 SetVector
<sys::Path
>& set
,
567 // First, see if the unadorned file name is not readable. If so,
568 // we must track down the file in the lib search path.
570 if (!link_item
.canRead()) {
571 // look for the library using the -L arguments specified
572 // on the command line.
573 fullpath
= GetPathForLinkageItem(link_item
.toString());
575 // If we didn't find the file in any of the library search paths
576 // we have to bail. No where else to look.
577 if (fullpath
.isEmpty()) {
579 std::string("Can't find linkage item '") + link_item
.toString() + "'";
583 fullpath
= link_item
;
586 // If we got here fullpath is the path to the file, and its readable.
587 set
.insert(fullpath
);
589 // If its an LLVM bitcode file ...
590 if (fullpath
.isBitcodeFile()) {
591 // Process the dependent libraries recursively
592 Module::LibraryListType modlibs
;
593 if (GetBitcodeDependentLibraries(fullpath
.toString(),modlibs
, &err
)) {
594 // Traverse the dependent libraries list
595 Module::lib_iterator LI
= modlibs
.begin();
596 Module::lib_iterator LE
= modlibs
.end();
598 if (!ProcessLinkageItem(sys::Path(*LI
),set
,err
)) {
600 err
= std::string("Library '") + *LI
+
601 "' is not valid for linking but is required by file '" +
602 fullpath
.toString() + "'";
604 err
+= " which is required by file '" + fullpath
.toString() + "'";
610 } else if (err
.empty()) {
612 "The dependent libraries could not be extracted from '") +
625 virtual int execute(const InputList
& InpList
, const sys::Path
& Output
, std::string
& ErrMsg
) {
627 // Echo the configuration of options if we're running verbose
628 if (isSet(DEBUG_FLAG
)) {
629 std::cerr
<< "Compiler Driver Options:\n";
630 std::cerr
<< "DryRun = " << isSet(DRY_RUN_FLAG
) << "\n";
631 std::cerr
<< "Verbose = " << isSet(VERBOSE_FLAG
) << " \n";
632 std::cerr
<< "TimeActions = " << isSet(TIME_ACTIONS_FLAG
) << "\n";
633 std::cerr
<< "TimePasses = " << isSet(TIME_PASSES_FLAG
) << "\n";
634 std::cerr
<< "ShowStats = " << isSet(SHOW_STATS_FLAG
) << "\n";
635 std::cerr
<< "EmitRawCode = " << isSet(EMIT_RAW_FLAG
) << "\n";
636 std::cerr
<< "EmitNativeCode = " << isSet(EMIT_NATIVE_FLAG
) << "\n";
637 std::cerr
<< "KeepTemps = " << isSet(KEEP_TEMPS_FLAG
) << "\n";
638 std::cerr
<< "OutputMachine = " << machine
<< "\n";
639 InputList::const_iterator I
= InpList
.begin();
640 while ( I
!= InpList
.end() ) {
641 std::cerr
<< "Input: " << I
->first
<< "(" << I
->second
645 std::cerr
<< "Output: " << Output
<< "\n";
648 // If there's no input, we're done.
650 throw std::string("Nothing to compile.");
652 // If they are asking for linking and didn't provide an output
653 // file then its an error (no way for us to "make up" a meaningful
654 // file name based on the various linker input files).
655 if (finalPhase
== LINKING
&& Output
.isEmpty())
657 "An output file name must be specified for linker output");
659 // If they are not asking for linking, provided an output file and
660 // there is more than one input file, its an error
661 if (finalPhase
!= LINKING
&& !Output
.isEmpty() && InpList
.size() > 1)
662 throw std::string("An output file name cannot be specified ") +
663 "with more than one input file name when not linking";
665 // This vector holds all the resulting actions of the following loop.
666 std::vector
<Action
*> actions
;
668 /// PRE-PROCESSING / TRANSLATION / OPTIMIZATION / ASSEMBLY phases
669 // for each input item
670 SetVector
<sys::Path
> LinkageItems
;
671 StringVector LibFiles
;
672 InputList::const_iterator I
= InpList
.begin();
673 for (InputList::const_iterator I
= InpList
.begin(), E
= InpList
.end();
675 // Get the suffix of the file name
676 const std::string
& ftype
= I
->second
;
678 // If its a library, bitcode file, or object file, save
679 // it for linking below and short circuit the
680 // pre-processing/translation/assembly phases
681 if (ftype
.empty() || ftype
== "o" || ftype
== "bc" || ftype
=="a") {
682 // We shouldn't get any of these types of files unless we're
683 // later going to link. Enforce this limit now.
684 if (finalPhase
!= LINKING
) {
686 "Pre-compiled objects found but linking not requested");
689 LibFiles
.push_back(I
->first
.toString());
691 LinkageItems
.insert(I
->first
);
692 continue; // short circuit remainder of loop
695 // At this point, we know its something we need to translate
696 // and/or optimize. See if we can get the configuration data
697 // for this kind of file.
698 ConfigData
* cd
= cdp
->ProvideConfigData(I
->second
);
700 throw std::string("Files of type '") + I
->second
+
701 "' are not recognized.";
702 if (isSet(DEBUG_FLAG
))
703 DumpConfigData(cd
,I
->second
);
705 // Add the config data's library paths to the end of the list
706 for (StringVector::iterator LPI
= cd
->libpaths
.begin(),
707 LPE
= cd
->libpaths
.end(); LPI
!= LPE
; ++LPI
){
708 LibraryPaths
.push_back(sys::Path(*LPI
));
711 // Initialize the input and output files
712 sys::Path
InFile(I
->first
);
713 sys::Path
OutFile(I
->first
.getBasename());
715 // PRE-PROCESSING PHASE
716 Action
& action
= cd
->PreProcessor
;
718 // Get the preprocessing action, if needed, or error if appropriate
719 if (!action
.program
.isEmpty()) {
720 if (action
.isSet(REQUIRED_FLAG
) || finalPhase
== PREPROCESSING
) {
721 if (finalPhase
== PREPROCESSING
) {
722 if (Output
.isEmpty()) {
723 OutFile
.appendSuffix("E");
724 actions
.push_back(GetAction(cd
,InFile
,OutFile
,PREPROCESSING
));
726 actions
.push_back(GetAction(cd
,InFile
,Output
,PREPROCESSING
));
730 MakeTempFile(I
->first
.getBasename(),"E",&ErrMsg
));
731 if (TempFile
.isEmpty())
733 actions
.push_back(GetAction(cd
,InFile
,TempFile
,
738 } else if (finalPhase
== PREPROCESSING
) {
739 throw cd
->langName
+ " does not support pre-processing";
740 } else if (action
.isSet(REQUIRED_FLAG
)) {
741 throw std::string("Don't know how to pre-process ") +
742 cd
->langName
+ " files";
745 // Short-circuit remaining actions if all they want is
747 if (finalPhase
== PREPROCESSING
) { continue; };
749 /// TRANSLATION PHASE
750 action
= cd
->Translator
;
752 // Get the translation action, if needed, or error if appropriate
753 if (!action
.program
.isEmpty()) {
754 if (action
.isSet(REQUIRED_FLAG
) || finalPhase
== TRANSLATION
) {
755 if (finalPhase
== TRANSLATION
) {
756 if (Output
.isEmpty()) {
757 OutFile
.appendSuffix("o");
758 actions
.push_back(GetAction(cd
,InFile
,OutFile
,TRANSLATION
));
760 actions
.push_back(GetAction(cd
,InFile
,Output
,TRANSLATION
));
764 MakeTempFile(I
->first
.getBasename(),"trans", &ErrMsg
));
765 if (TempFile
.isEmpty())
767 actions
.push_back(GetAction(cd
,InFile
,TempFile
,TRANSLATION
));
772 if (action
.isSet(OUTPUT_IS_ASM_FLAG
)) {
773 /// The output of the translator is an LLVM Assembly program
774 /// We need to translate it to bitcode
775 Action
* action
= new Action();
776 action
->program
.set("llvm-as");
777 action
->args
.push_back(InFile
.toString());
778 action
->args
.push_back("-o");
779 InFile
.appendSuffix("bc");
780 action
->args
.push_back(InFile
.toString());
781 actions
.push_back(action
);
784 } else if (finalPhase
== TRANSLATION
) {
785 throw cd
->langName
+ " does not support translation";
786 } else if (action
.isSet(REQUIRED_FLAG
)) {
787 throw std::string("Don't know how to translate ") +
788 cd
->langName
+ " files";
791 // Short-circuit remaining actions if all they want is translation
792 if (finalPhase
== TRANSLATION
) { continue; }
794 /// OPTIMIZATION PHASE
795 action
= cd
->Optimizer
;
797 // Get the optimization action, if needed, or error if appropriate
798 if (!isSet(EMIT_RAW_FLAG
)) {
799 if (!action
.program
.isEmpty()) {
800 if (action
.isSet(REQUIRED_FLAG
) || finalPhase
== OPTIMIZATION
) {
801 if (finalPhase
== OPTIMIZATION
) {
802 if (Output
.isEmpty()) {
803 OutFile
.appendSuffix("o");
804 actions
.push_back(GetAction(cd
,InFile
,OutFile
,OPTIMIZATION
));
806 actions
.push_back(GetAction(cd
,InFile
,Output
,OPTIMIZATION
));
810 MakeTempFile(I
->first
.getBasename(),"opt", &ErrMsg
));
811 if (TempFile
.isEmpty())
813 actions
.push_back(GetAction(cd
,InFile
,TempFile
,OPTIMIZATION
));
817 if (action
.isSet(OUTPUT_IS_ASM_FLAG
)) {
818 /// The output of the optimizer is an LLVM Assembly program
819 /// We need to translate it to bitcode with llvm-as
820 Action
* action
= new Action();
821 action
->program
.set("llvm-as");
822 action
->args
.push_back(InFile
.toString());
823 action
->args
.push_back("-f");
824 action
->args
.push_back("-o");
825 InFile
.appendSuffix("bc");
826 action
->args
.push_back(InFile
.toString());
827 actions
.push_back(action
);
830 } else if (finalPhase
== OPTIMIZATION
) {
831 throw cd
->langName
+ " does not support optimization";
832 } else if (action
.isSet(REQUIRED_FLAG
)) {
833 throw std::string("Don't know how to optimize ") +
834 cd
->langName
+ " files";
838 // Short-circuit remaining actions if all they want is optimization
839 if (finalPhase
== OPTIMIZATION
) { continue; }
842 action
= cd
->Assembler
;
844 if (finalPhase
== ASSEMBLY
) {
846 // Build either a native compilation action or a disassembly action
847 Action
* action
= new Action();
848 if (isSet(EMIT_NATIVE_FLAG
)) {
849 // Use llc to get the native assembly file
850 action
->program
.set("llc");
851 action
->args
.push_back(InFile
.toString());
852 action
->args
.push_back("-f");
853 action
->args
.push_back("-o");
854 if (Output
.isEmpty()) {
855 OutFile
.appendSuffix("o");
856 action
->args
.push_back(OutFile
.toString());
858 action
->args
.push_back(Output
.toString());
860 actions
.push_back(action
);
862 // Just convert back to llvm assembly with llvm-dis
863 action
->program
.set("llvm-dis");
864 action
->args
.push_back(InFile
.toString());
865 action
->args
.push_back("-f");
866 action
->args
.push_back("-o");
867 if (Output
.isEmpty()) {
868 OutFile
.appendSuffix("ll");
869 action
->args
.push_back(OutFile
.toString());
871 action
->args
.push_back(Output
.toString());
875 // Put the action on the list
876 actions
.push_back(action
);
878 // Short circuit the rest of the loop, we don't want to link
882 // Register the result of the actions as a link candidate
883 LinkageItems
.insert(InFile
);
885 } // end while loop over each input file
887 /// RUN THE COMPILATION ACTIONS
888 std::vector
<Action
*>::iterator AI
= actions
.begin();
889 std::vector
<Action
*>::iterator AE
= actions
.end();
891 int ActionResult
= DoAction(*AI
, ErrMsg
);
892 if (ActionResult
!= 0)
898 if (finalPhase
== LINKING
) {
900 // Insert the platform-specific system libraries to the path list
901 std::vector
<sys::Path
> SysLibs
;
902 sys::Path::GetSystemLibraryPaths(SysLibs
);
903 LibraryPaths
.insert(LibraryPaths
.end(), SysLibs
.begin(), SysLibs
.end());
905 // Set up the linking action with llvm-ld
906 Action
* link
= new Action();
907 link
->program
.set("llvm-ld");
909 // Add in the optimization level requested
911 case OPT_FAST_COMPILE
:
912 link
->args
.push_back("-O1");
915 link
->args
.push_back("-O2");
918 link
->args
.push_back("-O3");
921 link
->args
.push_back("-O4");
923 case OPT_AGGRESSIVE_LINK_TIME
:
924 link
->args
.push_back("-O5");
930 // Add in all the linkage items we generated. This includes the
931 // output from the translation/optimization phases as well as any
932 // -l arguments specified.
933 for (PathVector::const_iterator I
=LinkageItems
.begin(),
934 E
=LinkageItems
.end(); I
!= E
; ++I
)
935 link
->args
.push_back(I
->toString());
937 // Add in all the libraries we found.
938 for (StringVector::const_iterator I
=LibFiles
.begin(),
939 E
=LibFiles
.end(); I
!= E
; ++I
)
940 link
->args
.push_back(std::string("-l")+*I
);
942 // Add in all the library paths to the command line
943 for (PathVector::const_iterator I
=LibraryPaths
.begin(),
944 E
=LibraryPaths
.end(); I
!= E
; ++I
)
945 link
->args
.push_back( std::string("-L") + I
->toString());
947 // Add in the additional linker arguments requested
948 for (StringVector::const_iterator I
=AdditionalArgs
[LINKING
].begin(),
949 E
=AdditionalArgs
[LINKING
].end(); I
!= E
; ++I
)
950 link
->args
.push_back( *I
);
952 // Add in other optional flags
953 if (isSet(EMIT_NATIVE_FLAG
))
954 link
->args
.push_back("-native");
955 if (isSet(VERBOSE_FLAG
))
956 link
->args
.push_back("-v");
957 if (isSet(TIME_PASSES_FLAG
))
958 link
->args
.push_back("-time-passes");
959 if (isSet(SHOW_STATS_FLAG
))
960 link
->args
.push_back("-stats");
961 if (isSet(STRIP_OUTPUT_FLAG
))
962 link
->args
.push_back("-s");
963 if (isSet(DEBUG_FLAG
)) {
964 link
->args
.push_back("-debug");
965 link
->args
.push_back("-debug-pass=Details");
968 // Add in mandatory flags
969 link
->args
.push_back("-o");
970 link
->args
.push_back(Output
.toString());
973 int ActionResult
= DoAction(link
, ErrMsg
);
974 if (ActionResult
!= 0)
977 } catch (std::string
& msg
) {
982 throw std::string("Unspecified error");
992 ConfigDataProvider
* cdp
; ///< Where we get configuration data from
993 Phases finalPhase
; ///< The final phase of compilation
994 OptimizationLevels optLevel
; ///< The optimization level to apply
995 unsigned Flags
; ///< The driver flags
996 std::string machine
; ///< Target machine name
997 PathVector LibraryPaths
; ///< -L options
998 PathVector IncludePaths
; ///< -I options
999 PathVector ToolPaths
; ///< -B options
1000 StringVector Defines
; ///< -D options
1001 sys::PathWithStatus TempDir
; ///< Name of the temporary directory.
1002 StringTable AdditionalArgs
; ///< The -Txyz options
1003 StringVector fOptions
; ///< -f options
1004 StringVector MOptions
; ///< -M options
1005 StringVector WOptions
; ///< -W options
1011 CompilerDriver::~CompilerDriver() {
1014 CompilerDriver::ConfigDataProvider::~ConfigDataProvider() {}
1017 CompilerDriver::Get(ConfigDataProvider
& CDP
) {
1018 return new CompilerDriverImpl(CDP
);
1021 CompilerDriver::ConfigData::ConfigData()
1029 StringVector emptyVec
;
1030 for (unsigned i
= 0; i
< NUM_PHASES
; ++i
)
1031 opts
.push_back(emptyVec
);