fdbfb886113c793f5a0c9ff68cbfefe4919beb59
[oota-llvm.git] / tools / llvmc2 / Action.cpp
1 //===--- Tools.h - The LLVM Compiler Driver ---------------------*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open
6 // Source License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 //  Action class - implementation and auxiliary functions.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "Action.h"
15
16 #include "llvm/Support/CommandLine.h"
17 #include "llvm/System/Program.h"
18
19 #include <iostream>
20 #include <stdexcept>
21
22 using namespace llvm;
23 using namespace llvmc;
24
25 extern cl::opt<bool> VerboseMode;
26
27 namespace {
28   int ExecuteProgram(const std::string& name,
29                      const StringVector& args) {
30     sys::Path prog = sys::Program::FindProgramByName(name);
31
32     if (prog.isEmpty())
33       throw std::runtime_error("Can't find program '" + name + "'");
34     if (!prog.canExecute())
35       throw std::runtime_error("Program '" + name + "' is not executable.");
36
37     const sys::Path* redirects[3] = {0,0,0};
38     sys::Path stdout_redirect;
39
40     std::vector<const char*> argv;
41     argv.reserve((args.size()+2));
42     argv.push_back(name.c_str());
43
44     for (StringVector::const_iterator B = args.begin(), E = args.end();
45          B!=E; ++B) {
46       if (*B == ">") {
47         ++B;
48         stdout_redirect.set(*B);
49         redirects[1] = &stdout_redirect;
50       }
51       else {
52         argv.push_back((*B).c_str());
53       }
54     }
55     argv.push_back(0);  // null terminate list.
56
57     return sys::Program::ExecuteAndWait(prog, &argv[0], 0, &redirects[0]);
58   }
59
60   void print_string (const std::string& str) {
61     std::cerr << str << ' ';
62   }
63 }
64
65 int llvmc::Action::Execute() const {
66   if (VerboseMode) {
67     std::cerr << Command_ << " ";
68     std::for_each(Args_.begin(), Args_.end(), print_string);
69     std::cerr << '\n';
70   }
71   return ExecuteProgram(Command_, Args_);
72 }