• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2016 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #include "Driver.h"
18 
19 #include <err.h>
20 #include <string.h>
21 
22 #include <chrono>
23 #include <mutex>
24 #include <string>
25 #include <thread>
26 #include <unordered_map>
27 #include <vector>
28 
29 #include <clang/AST/ASTConsumer.h>
30 #include <clang/Basic/Diagnostic.h>
31 #include <clang/Basic/TargetInfo.h>
32 #include <clang/Driver/Compilation.h>
33 #include <clang/Driver/Driver.h>
34 #include <clang/Frontend/CompilerInstance.h>
35 #include <clang/Frontend/CompilerInvocation.h>
36 #include <clang/Frontend/FrontendAction.h>
37 #include <clang/Frontend/FrontendActions.h>
38 #include <clang/Frontend/TextDiagnosticPrinter.h>
39 #include <clang/Frontend/Utils.h>
40 #include <clang/FrontendTool/Utils.h>
41 #include <llvm/ADT/IntrusiveRefCntPtr.h>
42 #include <llvm/ADT/SmallVector.h>
43 #include <llvm/ADT/StringRef.h>
44 #include <llvm/Option/Option.h>
45 #include <llvm/Support/VirtualFileSystem.h>
46 
47 #include "Arch.h"
48 #include "DeclarationDatabase.h"
49 #include "versioner.h"
50 
51 using namespace std::chrono_literals;
52 using namespace std::string_literals;
53 
54 using namespace clang;
55 
56 class VersionerASTConsumer : public clang::ASTConsumer {
57  public:
58   HeaderDatabase* header_database;
59   CompilationType type;
60 
VersionerASTConsumer(HeaderDatabase * header_database,CompilationType type)61   VersionerASTConsumer(HeaderDatabase* header_database, CompilationType type)
62       : header_database(header_database), type(type) {
63   }
64 
HandleTranslationUnit(ASTContext & ctx)65   void HandleTranslationUnit(ASTContext& ctx) override {
66     header_database->parseAST(type, ctx);
67   }
68 };
69 
70 class VersionerASTAction : public clang::ASTFrontendAction {
71  public:
72   HeaderDatabase* header_database;
73   CompilationType type;
74 
VersionerASTAction(HeaderDatabase * header_database,CompilationType type)75   VersionerASTAction(HeaderDatabase* header_database, CompilationType type)
76       : header_database(header_database), type(type) {
77   }
78 
CreateASTConsumer(CompilerInstance &,llvm::StringRef)79   std::unique_ptr<ASTConsumer> CreateASTConsumer(CompilerInstance&, llvm::StringRef) override {
80     return std::make_unique<VersionerASTConsumer>(header_database, type);
81   }
82 };
83 
constructDiags()84 static IntrusiveRefCntPtr<DiagnosticsEngine> constructDiags() {
85   IntrusiveRefCntPtr<DiagnosticOptions> diag_opts(new DiagnosticOptions());
86   auto diag_printer = std::make_unique<TextDiagnosticPrinter>(llvm::errs(), diag_opts.get());
87   IntrusiveRefCntPtr<DiagnosticIDs> diag_ids(new DiagnosticIDs());
88   IntrusiveRefCntPtr<DiagnosticsEngine> diags(
89       new DiagnosticsEngine(diag_ids.get(), diag_opts.get(), diag_printer.release()));
90   return diags;
91 }
92 
93 // clang's driver is slow compared to the work it performs to compile our headers.
94 // Run it once to generate flags for each target, and memoize the results.
95 static std::unordered_map<CompilationType, std::vector<std::string>> cc1_flags;
96 static const char* filename_placeholder = "__VERSIONER_PLACEHOLDER__";
generateTargetCC1Flags(llvm::IntrusiveRefCntPtr<llvm::vfs::FileSystem> vfs,CompilationType type,const std::vector<std::string> & include_dirs)97 static void generateTargetCC1Flags(llvm::IntrusiveRefCntPtr<llvm::vfs::FileSystem> vfs,
98                                    CompilationType type,
99                                    const std::vector<std::string>& include_dirs) {
100   std::vector<std::string> cmd = { "versioner" };
101   if (type.cpp) {
102     cmd.push_back("-std=gnu++11");
103     cmd.push_back("-x");
104     cmd.push_back("c++");
105   } else {
106     cmd.push_back("-std=gnu11");
107     cmd.push_back("-x");
108     cmd.push_back("c");
109   }
110 
111   cmd.push_back("-fsyntax-only");
112 
113   cmd.push_back("-Wall");
114   cmd.push_back("-Wextra");
115   cmd.push_back("-Weverything");
116   cmd.push_back("-Werror");
117   cmd.push_back("-Wundef");
118   cmd.push_back("-Wno-unused-macros");
119   cmd.push_back("-Wno-unused-function");
120   cmd.push_back("-Wno-unused-variable");
121   cmd.push_back("-Wno-unknown-attributes");
122   cmd.push_back("-Wno-pragma-once-outside-header");
123 
124   cmd.push_back("-target");
125   cmd.push_back(arch_targets[type.arch]);
126 
127   cmd.push_back("-DANDROID");
128   cmd.push_back("-D__BIONIC_VERSIONER=1");
129   cmd.push_back("-D__ANDROID_API__="s + std::to_string(type.api_level));
130   cmd.push_back("-D_FORTIFY_SOURCE=2");
131   cmd.push_back("-D_GNU_SOURCE");
132   cmd.push_back("-D_FILE_OFFSET_BITS="s + std::to_string(type.file_offset_bits));
133 
134   cmd.push_back("-nostdinc");
135 
136   if (add_include) {
137     cmd.push_back("-include");
138     cmd.push_back("android/versioning.h");
139   }
140 
141   for (const auto& dir : include_dirs) {
142     cmd.push_back("-isystem");
143     cmd.push_back(dir);
144   }
145 
146   cmd.push_back("-include");
147   cmd.push_back(filename_placeholder);
148   cmd.push_back("-");
149 
150   auto diags = constructDiags();
151   driver::Driver driver("versioner", llvm::sys::getDefaultTargetTriple(), *diags, vfs);
152   driver.setCheckInputsExist(false);
153 
154   llvm::SmallVector<const char*, 32> driver_args;
155   for (const std::string& str : cmd) {
156     driver_args.push_back(str.c_str());
157   }
158 
159   std::unique_ptr<driver::Compilation> Compilation(driver.BuildCompilation(driver_args));
160   const driver::JobList& jobs = Compilation->getJobs();
161   if (jobs.size() != 1) {
162     errx(1, "driver returned %zu jobs for %s", jobs.size(), to_string(type).c_str());
163   }
164 
165   const driver::Command& driver_cmd = llvm::cast<driver::Command>(*jobs.begin());
166   const llvm::opt::ArgStringList& cc_args = driver_cmd.getArguments();
167 
168   if (cc_args.size() == 0) {
169     errx(1, "driver returned empty command for %s", to_string(type).c_str());
170   }
171 
172   std::vector<std::string> result(cc_args.begin(), cc_args.end());
173 
174   {
175     static std::mutex cc1_init_mutex;
176     std::unique_lock<std::mutex> lock(cc1_init_mutex);
177     if (cc1_flags.count(type) > 0) {
178       errx(1, "attemped to generate cc1 flags for existing CompilationType %s",
179            to_string(type).c_str());
180     }
181 
182     cc1_flags.emplace(std::make_pair(type, std::move(result)));
183   }
184 }
185 
getCC1Command(CompilationType type,const std::string & filename)186 static std::vector<const char*> getCC1Command(CompilationType type, const std::string& filename) {
187   const auto& target_flag_it = cc1_flags.find(type);
188   if (target_flag_it == cc1_flags.end()) {
189     errx(1, "failed to find target flags for CompilationType %s", to_string(type).c_str());
190   }
191 
192   std::vector<const char*> result;
193   for (const std::string& flag : target_flag_it->second) {
194     if (flag == "-disable-free") {
195       continue;
196     } else if (flag == filename_placeholder) {
197       result.push_back(filename.c_str());
198     } else {
199       result.push_back(flag.c_str());
200     }
201   }
202   return result;
203 }
204 
initializeTargetCC1FlagCache(llvm::IntrusiveRefCntPtr<llvm::vfs::FileSystem> vfs,const std::set<CompilationType> & types,const std::unordered_map<Arch,CompilationRequirements> & reqs)205 void initializeTargetCC1FlagCache(llvm::IntrusiveRefCntPtr<llvm::vfs::FileSystem> vfs,
206                                   const std::set<CompilationType>& types,
207                                   const std::unordered_map<Arch, CompilationRequirements>& reqs) {
208   if (!cc1_flags.empty()) {
209     errx(1, "reinitializing target CC1 flag cache?");
210   }
211 
212   auto start = std::chrono::high_resolution_clock::now();
213   std::vector<std::thread> threads;
214   for (const CompilationType type : types) {
215     threads.emplace_back([type, &vfs, &reqs]() {
216       const auto& arch_req_it = reqs.find(type.arch);
217       if (arch_req_it == reqs.end()) {
218         errx(1, "CompilationRequirement map missing entry for CompilationType %s",
219              to_string(type).c_str());
220       }
221 
222       generateTargetCC1Flags(vfs, type, arch_req_it->second.dependencies);
223     });
224   }
225   for (auto& thread : threads) {
226     thread.join();
227   }
228   auto end = std::chrono::high_resolution_clock::now();
229 
230   if (verbose) {
231     auto diff = (end - start) / 1.0ms;
232     printf("Generated compiler flags for %zu targets in %0.2Lfms\n", types.size(), diff);
233   }
234 
235   if (cc1_flags.empty()) {
236     errx(1, "failed to initialize target CC1 flag cache");
237   }
238 }
239 
compileHeader(llvm::IntrusiveRefCntPtr<llvm::vfs::FileSystem> vfs,HeaderDatabase * header_database,CompilationType type,const std::string & filename)240 void compileHeader(llvm::IntrusiveRefCntPtr<llvm::vfs::FileSystem> vfs,
241                    HeaderDatabase* header_database, CompilationType type,
242                    const std::string& filename) {
243   auto diags = constructDiags();
244   std::vector<const char*> cc1_flags = getCC1Command(type, filename);
245   auto invocation = std::make_unique<CompilerInvocation>();
246   if (!CompilerInvocation::CreateFromArgs(*invocation.get(), cc1_flags, *diags)) {
247     errx(1, "failed to create CompilerInvocation");
248   }
249 
250   clang::CompilerInstance Compiler;
251 
252   Compiler.setInvocation(std::move(invocation));
253   Compiler.setDiagnostics(diags.get());
254   Compiler.createFileManager(vfs);
255 
256   VersionerASTAction versioner_action(header_database, type);
257   if (!Compiler.ExecuteAction(versioner_action)) {
258     errx(1, "compilation generated warnings or errors");
259   }
260 
261   if (diags->getNumWarnings() || diags->hasErrorOccurred()) {
262     errx(1, "compilation generated warnings or errors");
263   }
264 }
265