blob: a094818380b97edc081c8408f8c3ea0b6cc68c6a [file] [log] [blame]
Josh Gaob5c49632016-11-08 22:21:31 -08001/*
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>
Josh Gao78b8a142016-11-09 01:00:41 -080032#include <clang/Basic/VirtualFileSystem.h>
Josh Gaob5c49632016-11-08 22:21:31 -080033#include <clang/Driver/Compilation.h>
34#include <clang/Driver/Driver.h>
35#include <clang/Frontend/CompilerInstance.h>
36#include <clang/Frontend/CompilerInvocation.h>
37#include <clang/Frontend/FrontendAction.h>
38#include <clang/Frontend/FrontendActions.h>
39#include <clang/Frontend/TextDiagnosticPrinter.h>
40#include <clang/Frontend/Utils.h>
41#include <clang/FrontendTool/Utils.h>
42#include <llvm/ADT/IntrusiveRefCntPtr.h>
43#include <llvm/ADT/SmallVector.h>
44#include <llvm/ADT/StringRef.h>
Yi Kong06be3452017-04-20 14:27:28 -070045#include <llvm/Config/config.h>
Josh Gaob5c49632016-11-08 22:21:31 -080046
47#include "Arch.h"
48#include "DeclarationDatabase.h"
49#include "versioner.h"
50
51using namespace std::chrono_literals;
52using namespace std::string_literals;
53
54using namespace clang;
55
56class VersionerASTConsumer : public clang::ASTConsumer {
57 public:
58 HeaderDatabase* header_database;
59 CompilationType type;
60
61 VersionerASTConsumer(HeaderDatabase* header_database, CompilationType type)
62 : header_database(header_database), type(type) {
63 }
64
65 virtual void HandleTranslationUnit(ASTContext& ctx) override {
66 header_database->parseAST(type, ctx);
67 }
68};
69
70class VersionerASTAction : public clang::ASTFrontendAction {
71 public:
72 HeaderDatabase* header_database;
73 CompilationType type;
74
75 VersionerASTAction(HeaderDatabase* header_database, CompilationType type)
76 : header_database(header_database), type(type) {
77 }
78
79 std::unique_ptr<ASTConsumer> CreateASTConsumer(CompilerInstance&, llvm::StringRef) override {
80 return std::make_unique<VersionerASTConsumer>(header_database, type);
81 }
82};
83
84static 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.
95static std::unordered_map<CompilationType, std::vector<std::string>> cc1_flags;
96static const char* filename_placeholder = "__VERSIONER_PLACEHOLDER__";
Josh Gao78b8a142016-11-09 01:00:41 -080097static void generateTargetCC1Flags(llvm::IntrusiveRefCntPtr<clang::vfs::FileSystem> vfs,
98 CompilationType type,
Josh Gaob5c49632016-11-08 22:21:31 -080099 const std::vector<std::string>& include_dirs) {
100 std::vector<std::string> cmd = { "versioner" };
101 cmd.push_back("-std=c11");
102 cmd.push_back("-x");
Josh Gaod2ab9ff2017-07-28 12:53:36 -0700103 cmd.push_back("c");
Josh Gaob5c49632016-11-08 22:21:31 -0800104 cmd.push_back("-fsyntax-only");
105
106 cmd.push_back("-Wall");
107 cmd.push_back("-Wextra");
Josh Gaod2ab9ff2017-07-28 12:53:36 -0700108 cmd.push_back("-Weverything");
Josh Gaob5c49632016-11-08 22:21:31 -0800109 cmd.push_back("-Werror");
110 cmd.push_back("-Wundef");
111 cmd.push_back("-Wno-unused-macros");
112 cmd.push_back("-Wno-unused-function");
113 cmd.push_back("-Wno-unused-variable");
114 cmd.push_back("-Wno-unknown-attributes");
115 cmd.push_back("-Wno-pragma-once-outside-header");
116
117 cmd.push_back("-target");
118 cmd.push_back(arch_targets[type.arch]);
119
120 cmd.push_back("-DANDROID");
121 cmd.push_back("-D__ANDROID_API__="s + std::to_string(type.api_level));
122 cmd.push_back("-D_FORTIFY_SOURCE=2");
123 cmd.push_back("-D_GNU_SOURCE");
124 cmd.push_back("-D_FILE_OFFSET_BITS="s + std::to_string(type.file_offset_bits));
125
126 cmd.push_back("-nostdinc");
127
128 if (add_include) {
Josh Gaob5c49632016-11-08 22:21:31 -0800129 cmd.push_back("-include");
Josh Gao78b8a142016-11-09 01:00:41 -0800130 cmd.push_back("android/versioning.h");
Josh Gaob5c49632016-11-08 22:21:31 -0800131 }
132
133 for (const auto& dir : include_dirs) {
134 cmd.push_back("-isystem");
135 cmd.push_back(dir);
136 }
137
Josh Gaod2ab9ff2017-07-28 12:53:36 -0700138 cmd.push_back("-include");
Josh Gaob5c49632016-11-08 22:21:31 -0800139 cmd.push_back(filename_placeholder);
Josh Gaod2ab9ff2017-07-28 12:53:36 -0700140 cmd.push_back("-");
Josh Gaob5c49632016-11-08 22:21:31 -0800141
142 auto diags = constructDiags();
Josh Gao78b8a142016-11-09 01:00:41 -0800143 driver::Driver driver("versioner", llvm::sys::getDefaultTargetTriple(), *diags, vfs);
Josh Gaob5c49632016-11-08 22:21:31 -0800144 driver.setCheckInputsExist(false);
145
146 llvm::SmallVector<const char*, 32> driver_args;
147 for (const std::string& str : cmd) {
148 driver_args.push_back(str.c_str());
149 }
150
151 std::unique_ptr<driver::Compilation> Compilation(driver.BuildCompilation(driver_args));
152 const driver::JobList& jobs = Compilation->getJobs();
153 if (jobs.size() != 1) {
154 errx(1, "driver returned %zu jobs for %s", jobs.size(), to_string(type).c_str());
155 }
156
157 const driver::Command& driver_cmd = llvm::cast<driver::Command>(*jobs.begin());
158 const driver::ArgStringList& cc_args = driver_cmd.getArguments();
159
160 if (cc_args.size() == 0) {
161 errx(1, "driver returned empty command for %s", to_string(type).c_str());
162 }
163
164 std::vector<std::string> result(cc_args.begin(), cc_args.end());
165
166 {
167 static std::mutex cc1_init_mutex;
168 std::unique_lock<std::mutex> lock(cc1_init_mutex);
169 if (cc1_flags.count(type) > 0) {
170 errx(1, "attemped to generate cc1 flags for existing CompilationType %s",
171 to_string(type).c_str());
172 }
173
174 cc1_flags.emplace(std::make_pair(type, std::move(result)));
175 }
176}
177
178static std::vector<const char*> getCC1Command(CompilationType type, const std::string& filename) {
179 const auto& target_flag_it = cc1_flags.find(type);
180 if (target_flag_it == cc1_flags.end()) {
181 errx(1, "failed to find target flags for CompilationType %s", to_string(type).c_str());
182 }
183
184 std::vector<const char*> result;
185 for (const std::string& flag : target_flag_it->second) {
186 if (flag == "-disable-free") {
187 continue;
188 } else if (flag == filename_placeholder) {
189 result.push_back(filename.c_str());
190 } else {
191 result.push_back(flag.c_str());
192 }
193 }
194 return result;
195}
196
Josh Gao78b8a142016-11-09 01:00:41 -0800197void initializeTargetCC1FlagCache(llvm::IntrusiveRefCntPtr<clang::vfs::FileSystem> vfs,
198 const std::set<CompilationType>& types,
Josh Gaob5c49632016-11-08 22:21:31 -0800199 const std::unordered_map<Arch, CompilationRequirements>& reqs) {
200 if (!cc1_flags.empty()) {
201 errx(1, "reinitializing target CC1 flag cache?");
202 }
203
204 auto start = std::chrono::high_resolution_clock::now();
205 std::vector<std::thread> threads;
206 for (const CompilationType type : types) {
Josh Gao78b8a142016-11-09 01:00:41 -0800207 threads.emplace_back([type, &vfs, &reqs]() {
Josh Gaob5c49632016-11-08 22:21:31 -0800208 const auto& arch_req_it = reqs.find(type.arch);
209 if (arch_req_it == reqs.end()) {
210 errx(1, "CompilationRequirement map missing entry for CompilationType %s",
211 to_string(type).c_str());
212 }
213
Josh Gao78b8a142016-11-09 01:00:41 -0800214 generateTargetCC1Flags(vfs, type, arch_req_it->second.dependencies);
Josh Gaob5c49632016-11-08 22:21:31 -0800215 });
216 }
217 for (auto& thread : threads) {
218 thread.join();
219 }
220 auto end = std::chrono::high_resolution_clock::now();
221
222 if (verbose) {
223 auto diff = (end - start) / 1.0ms;
224 printf("Generated compiler flags for %zu targets in %0.2Lfms\n", types.size(), diff);
225 }
226
227 if (cc1_flags.empty()) {
228 errx(1, "failed to initialize target CC1 flag cache");
229 }
230}
231
Josh Gao78b8a142016-11-09 01:00:41 -0800232void compileHeader(llvm::IntrusiveRefCntPtr<clang::vfs::FileSystem> vfs,
233 HeaderDatabase* header_database, CompilationType type,
Josh Gaob5c49632016-11-08 22:21:31 -0800234 const std::string& filename) {
235 auto diags = constructDiags();
236 std::vector<const char*> cc1_flags = getCC1Command(type, filename);
237 auto invocation = std::make_unique<CompilerInvocation>();
238 if (!CompilerInvocation::CreateFromArgs(*invocation.get(), &cc1_flags.front(),
239 &cc1_flags.front() + cc1_flags.size(), *diags)) {
240 errx(1, "failed to create CompilerInvocation");
241 }
242
243 clang::CompilerInstance Compiler;
Yi Kong06be3452017-04-20 14:27:28 -0700244
245// Remove the workaround once b/35936936 is fixed.
246#if LLVM_VERSION_MAJOR >= 5
247 Compiler.setInvocation(std::move(invocation));
248#else
Josh Gaob5c49632016-11-08 22:21:31 -0800249 Compiler.setInvocation(invocation.release());
Yi Kong06be3452017-04-20 14:27:28 -0700250#endif
251
Josh Gaob5c49632016-11-08 22:21:31 -0800252 Compiler.setDiagnostics(diags.get());
Josh Gao78b8a142016-11-09 01:00:41 -0800253 Compiler.setVirtualFileSystem(vfs);
Josh Gaob5c49632016-11-08 22:21:31 -0800254
255 VersionerASTAction versioner_action(header_database, type);
256 if (!Compiler.ExecuteAction(versioner_action)) {
257 errx(1, "compilation generated warnings or errors");
258 }
259
260 if (diags->getNumWarnings() || diags->hasErrorOccurred()) {
261 errx(1, "compilation generated warnings or errors");
262 }
263}