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