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