1 //===--- Compilation.cpp - Compilation Task Implementation ----------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 
10 #include "clang/Driver/Compilation.h"
11 #include "clang/Driver/Action.h"
12 #include "clang/Driver/Driver.h"
13 #include "clang/Driver/DriverDiagnostic.h"
14 #include "clang/Driver/Options.h"
15 #include "clang/Driver/ToolChain.h"
16 #include "llvm/ADT/STLExtras.h"
17 #include "llvm/Option/ArgList.h"
18 #include "llvm/Support/FileSystem.h"
19 #include "llvm/Support/raw_ostream.h"
20 
21 using namespace clang::driver;
22 using namespace clang;
23 using namespace llvm::opt;
24 
25 Compilation::Compilation(const Driver &D, const ToolChain &_DefaultToolChain,
26                          InputArgList *_Args, DerivedArgList *_TranslatedArgs)
27     : TheDriver(D), DefaultToolChain(_DefaultToolChain), ActiveOffloadMask(0u),
28       Args(_Args), TranslatedArgs(_TranslatedArgs), Redirects(nullptr),
29       ForDiagnostics(false) {
30   // The offloading host toolchain is the default tool chain.
31   OrderedOffloadingToolchains.insert(
32       std::make_pair(Action::OFK_Host, &DefaultToolChain));
33 }
34 
35 Compilation::~Compilation() {
36   delete TranslatedArgs;
37   delete Args;
38 
39   // Free any derived arg lists.
40   for (auto Arg : TCArgs)
41     if (Arg.second != TranslatedArgs)
42       delete Arg.second;
43 
44   // Free redirections of stdout/stderr.
45   if (Redirects) {
46     delete Redirects[0];
47     delete Redirects[1];
48     delete Redirects[2];
49     delete [] Redirects;
50   }
51 }
52 
53 const DerivedArgList &Compilation::getArgsForToolChain(const ToolChain *TC,
54                                                        StringRef BoundArch) {
55   if (!TC)
56     TC = &DefaultToolChain;
57 
58   DerivedArgList *&Entry = TCArgs[std::make_pair(TC, BoundArch)];
59   if (!Entry) {
60     Entry = TC->TranslateArgs(*TranslatedArgs, BoundArch);
61     if (!Entry)
62       Entry = TranslatedArgs;
63   }
64 
65   return *Entry;
66 }
67 
68 bool Compilation::CleanupFile(const char *File, bool IssueErrors) const {
69   // FIXME: Why are we trying to remove files that we have not created? For
70   // example we should only try to remove a temporary assembly file if
71   // "clang -cc1" succeed in writing it. Was this a workaround for when
72   // clang was writing directly to a .s file and sometimes leaving it behind
73   // during a failure?
74 
75   // FIXME: If this is necessary, we can still try to split
76   // llvm::sys::fs::remove into a removeFile and a removeDir and avoid the
77   // duplicated stat from is_regular_file.
78 
79   // Don't try to remove files which we don't have write access to (but may be
80   // able to remove), or non-regular files. Underlying tools may have
81   // intentionally not overwritten them.
82   if (!llvm::sys::fs::can_write(File) || !llvm::sys::fs::is_regular_file(File))
83     return true;
84 
85   if (std::error_code EC = llvm::sys::fs::remove(File)) {
86     // Failure is only failure if the file exists and is "regular". We checked
87     // for it being regular before, and llvm::sys::fs::remove ignores ENOENT,
88     // so we don't need to check again.
89 
90     if (IssueErrors)
91       getDriver().Diag(clang::diag::err_drv_unable_to_remove_file)
92         << EC.message();
93     return false;
94   }
95   return true;
96 }
97 
98 bool Compilation::CleanupFileList(const ArgStringList &Files,
99                                   bool IssueErrors) const {
100   bool Success = true;
101   for (ArgStringList::const_iterator
102          it = Files.begin(), ie = Files.end(); it != ie; ++it)
103     Success &= CleanupFile(*it, IssueErrors);
104   return Success;
105 }
106 
107 bool Compilation::CleanupFileMap(const ArgStringMap &Files,
108                                  const JobAction *JA,
109                                  bool IssueErrors) const {
110   bool Success = true;
111   for (ArgStringMap::const_iterator
112          it = Files.begin(), ie = Files.end(); it != ie; ++it) {
113 
114     // If specified, only delete the files associated with the JobAction.
115     // Otherwise, delete all files in the map.
116     if (JA && it->first != JA)
117       continue;
118     Success &= CleanupFile(it->second, IssueErrors);
119   }
120   return Success;
121 }
122 
123 int Compilation::ExecuteCommand(const Command &C,
124                                 const Command *&FailingCommand) const {
125   if ((getDriver().CCPrintOptions ||
126        getArgs().hasArg(options::OPT_v)) && !getDriver().CCGenDiagnostics) {
127     raw_ostream *OS = &llvm::errs();
128 
129     // Follow gcc implementation of CC_PRINT_OPTIONS; we could also cache the
130     // output stream.
131     if (getDriver().CCPrintOptions && getDriver().CCPrintOptionsFilename) {
132       std::error_code EC;
133       OS = new llvm::raw_fd_ostream(getDriver().CCPrintOptionsFilename, EC,
134                                     llvm::sys::fs::F_Append |
135                                         llvm::sys::fs::F_Text);
136       if (EC) {
137         getDriver().Diag(clang::diag::err_drv_cc_print_options_failure)
138             << EC.message();
139         FailingCommand = &C;
140         delete OS;
141         return 1;
142       }
143     }
144 
145     if (getDriver().CCPrintOptions)
146       *OS << "[Logging clang options]";
147 
148     C.Print(*OS, "\n", /*Quote=*/getDriver().CCPrintOptions);
149 
150     if (OS != &llvm::errs())
151       delete OS;
152   }
153 
154   std::string Error;
155   bool ExecutionFailed;
156   int Res = C.Execute(Redirects, &Error, &ExecutionFailed);
157   if (!Error.empty()) {
158     assert(Res && "Error string set with 0 result code!");
159     getDriver().Diag(clang::diag::err_drv_command_failure) << Error;
160   }
161 
162   if (Res)
163     FailingCommand = &C;
164 
165   return ExecutionFailed ? 1 : Res;
166 }
167 
168 void Compilation::ExecuteJobs(
169     const JobList &Jobs,
170     SmallVectorImpl<std::pair<int, const Command *>> &FailingCommands) const {
171   for (const auto &Job : Jobs) {
172     const Command *FailingCommand = nullptr;
173     if (int Res = ExecuteCommand(Job, FailingCommand)) {
174       FailingCommands.push_back(std::make_pair(Res, FailingCommand));
175       // Bail as soon as one command fails, so we don't output duplicate error
176       // messages if we die on e.g. the same file.
177       return;
178     }
179   }
180 }
181 
182 void Compilation::initCompilationForDiagnostics() {
183   ForDiagnostics = true;
184 
185   // Free actions and jobs.
186   Actions.clear();
187   AllActions.clear();
188   Jobs.clear();
189 
190   // Clear temporary/results file lists.
191   TempFiles.clear();
192   ResultFiles.clear();
193   FailureResultFiles.clear();
194 
195   // Remove any user specified output.  Claim any unclaimed arguments, so as
196   // to avoid emitting warnings about unused args.
197   OptSpecifier OutputOpts[] = { options::OPT_o, options::OPT_MD,
198                                 options::OPT_MMD };
199   for (unsigned i = 0, e = llvm::array_lengthof(OutputOpts); i != e; ++i) {
200     if (TranslatedArgs->hasArg(OutputOpts[i]))
201       TranslatedArgs->eraseArg(OutputOpts[i]);
202   }
203   TranslatedArgs->ClaimAllArgs();
204 
205   // Redirect stdout/stderr to /dev/null.
206   Redirects = new const StringRef*[3]();
207   Redirects[0] = nullptr;
208   Redirects[1] = new StringRef();
209   Redirects[2] = new StringRef();
210 }
211 
212 StringRef Compilation::getSysRoot() const {
213   return getDriver().SysRoot;
214 }
215 
216 void Compilation::Redirect(const StringRef** Redirects) {
217   this->Redirects = Redirects;
218 }
219