codegen.c: directly include required headers
[isl.git] / interface / extract_interface.cc
blob3663ef760a0a91c6086828836c82cfafb69efa6d
1 /*
2 * Copyright 2011 Sven Verdoolaege. All rights reserved.
3 *
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions
6 * are met:
7 *
8 * 1. Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
11 * 2. Redistributions in binary form must reproduce the above
12 * copyright notice, this list of conditions and the following
13 * disclaimer in the documentation and/or other materials provided
14 * with the distribution.
16 * THIS SOFTWARE IS PROVIDED BY SVEN VERDOOLAEGE ''AS IS'' AND ANY
17 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
19 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SVEN VERDOOLAEGE OR
20 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
21 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
22 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
23 * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
24 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
26 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28 * The views and conclusions contained in the software and documentation
29 * are those of the authors and should not be interpreted as
30 * representing official policies, either expressed or implied, of
31 * Sven Verdoolaege.
32 */
34 #include "isl_config.h"
36 #include <assert.h>
37 #include <iostream>
38 #ifdef HAVE_ADT_OWNINGPTR_H
39 #include <llvm/ADT/OwningPtr.h>
40 #else
41 #include <memory>
42 #endif
43 #include <llvm/Support/raw_ostream.h>
44 #include <llvm/Support/CommandLine.h>
45 #include <llvm/Support/Host.h>
46 #include <llvm/Support/ManagedStatic.h>
47 #include <clang/AST/ASTContext.h>
48 #include <clang/AST/ASTConsumer.h>
49 #include <clang/Basic/FileSystemOptions.h>
50 #include <clang/Basic/FileManager.h>
51 #include <clang/Basic/TargetOptions.h>
52 #include <clang/Basic/TargetInfo.h>
53 #include <clang/Basic/Version.h>
54 #include <clang/Driver/Compilation.h>
55 #include <clang/Driver/Driver.h>
56 #include <clang/Driver/Tool.h>
57 #include <clang/Frontend/CompilerInstance.h>
58 #include <clang/Frontend/CompilerInvocation.h>
59 #ifdef HAVE_BASIC_DIAGNOSTICOPTIONS_H
60 #include <clang/Basic/DiagnosticOptions.h>
61 #else
62 #include <clang/Frontend/DiagnosticOptions.h>
63 #endif
64 #include <clang/Frontend/TextDiagnosticPrinter.h>
65 #include <clang/Frontend/Utils.h>
66 #include <clang/Lex/HeaderSearch.h>
67 #include <clang/Lex/Preprocessor.h>
68 #include <clang/Parse/ParseAST.h>
69 #include <clang/Sema/Sema.h>
71 #include "extract_interface.h"
72 #include "python.h"
74 using namespace std;
75 using namespace clang;
76 using namespace clang::driver;
78 #ifdef HAVE_ADT_OWNINGPTR_H
79 #define unique_ptr llvm::OwningPtr
80 #endif
82 static llvm::cl::opt<string> InputFilename(llvm::cl::Positional,
83 llvm::cl::Required, llvm::cl::desc("<input file>"));
84 static llvm::cl::list<string> Includes("I",
85 llvm::cl::desc("Header search path"),
86 llvm::cl::value_desc("path"), llvm::cl::Prefix);
88 static const char *ResourceDir =
89 CLANG_PREFIX "/lib/clang/" CLANG_VERSION_STRING;
91 /* Does decl have an attribute of the following form?
93 * __attribute__((annotate("name")))
95 bool has_annotation(Decl *decl, const char *name)
97 if (!decl->hasAttrs())
98 return false;
100 AttrVec attrs = decl->getAttrs();
101 for (AttrVec::const_iterator i = attrs.begin() ; i != attrs.end(); ++i) {
102 const AnnotateAttr *ann = dyn_cast<AnnotateAttr>(*i);
103 if (!ann)
104 continue;
105 if (ann->getAnnotation().str() == name)
106 return true;
109 return false;
112 /* Is decl marked as exported?
114 static bool is_exported(Decl *decl)
116 return has_annotation(decl, "isl_export");
119 /* Collect all types and functions that are annotated "isl_export"
120 * in "types" and "function".
122 * We currently only consider single declarations.
124 struct MyASTConsumer : public ASTConsumer {
125 set<RecordDecl *> types;
126 set<FunctionDecl *> functions;
128 virtual HandleTopLevelDeclReturn HandleTopLevelDecl(DeclGroupRef D) {
129 Decl *decl;
131 if (!D.isSingleDecl())
132 return HandleTopLevelDeclContinue;
133 decl = D.getSingleDecl();
134 if (!is_exported(decl))
135 return HandleTopLevelDeclContinue;
136 switch (decl->getKind()) {
137 case Decl::Record:
138 types.insert(cast<RecordDecl>(decl));
139 break;
140 case Decl::Function:
141 functions.insert(cast<FunctionDecl>(decl));
142 break;
143 default:
144 break;
146 return HandleTopLevelDeclContinue;
150 #ifdef USE_ARRAYREF
152 #ifdef HAVE_CXXISPRODUCTION
153 static Driver *construct_driver(const char *binary, DiagnosticsEngine &Diags)
155 return new Driver(binary, llvm::sys::getDefaultTargetTriple(),
156 "", false, false, Diags);
158 #elif defined(HAVE_ISPRODUCTION)
159 static Driver *construct_driver(const char *binary, DiagnosticsEngine &Diags)
161 return new Driver(binary, llvm::sys::getDefaultTargetTriple(),
162 "", false, Diags);
164 #elif defined(DRIVER_CTOR_TAKES_DEFAULTIMAGENAME)
165 static Driver *construct_driver(const char *binary, DiagnosticsEngine &Diags)
167 return new Driver(binary, llvm::sys::getDefaultTargetTriple(),
168 "", Diags);
170 #else
171 static Driver *construct_driver(const char *binary, DiagnosticsEngine &Diags)
173 return new Driver(binary, llvm::sys::getDefaultTargetTriple(), Diags);
175 #endif
177 /* Clang changed its API from 3.5 to 3.6, we fix this with a simple overloaded
178 * function here.
180 struct ClangAPI {
181 static Job *command(Job *J) { return J; }
182 static Job *command(Job &J) { return &J; }
185 /* Create a CompilerInvocation object that stores the command line
186 * arguments constructed by the driver.
187 * The arguments are mainly useful for setting up the system include
188 * paths on newer clangs and on some platforms.
190 static CompilerInvocation *construct_invocation(const char *filename,
191 DiagnosticsEngine &Diags)
193 const char *binary = CLANG_PREFIX"/bin/clang";
194 const unique_ptr<Driver> driver(construct_driver(binary, Diags));
195 std::vector<const char *> Argv;
196 Argv.push_back(binary);
197 Argv.push_back(filename);
198 const unique_ptr<Compilation> compilation(
199 driver->BuildCompilation(llvm::ArrayRef<const char *>(Argv)));
200 JobList &Jobs = compilation->getJobs();
202 Command *cmd = cast<Command>(ClangAPI::command(*Jobs.begin()));
203 if (strcmp(cmd->getCreator().getName(), "clang"))
204 return NULL;
206 const ArgStringList *args = &cmd->getArguments();
208 CompilerInvocation *invocation = new CompilerInvocation;
209 CompilerInvocation::CreateFromArgs(*invocation, args->data() + 1,
210 args->data() + args->size(),
211 Diags);
212 return invocation;
215 #else
217 static CompilerInvocation *construct_invocation(const char *filename,
218 DiagnosticsEngine &Diags)
220 return NULL;
223 #endif
225 #ifdef HAVE_BASIC_DIAGNOSTICOPTIONS_H
227 static TextDiagnosticPrinter *construct_printer(void)
229 return new TextDiagnosticPrinter(llvm::errs(), new DiagnosticOptions());
232 #else
234 static TextDiagnosticPrinter *construct_printer(void)
236 DiagnosticOptions DO;
237 return new TextDiagnosticPrinter(llvm::errs(), DO);
240 #endif
242 #ifdef CREATETARGETINFO_TAKES_SHARED_PTR
244 static TargetInfo *create_target_info(CompilerInstance *Clang,
245 DiagnosticsEngine &Diags)
247 shared_ptr<TargetOptions> TO = Clang->getInvocation().TargetOpts;
248 TO->Triple = llvm::sys::getDefaultTargetTriple();
249 return TargetInfo::CreateTargetInfo(Diags, TO);
252 #elif defined(CREATETARGETINFO_TAKES_POINTER)
254 static TargetInfo *create_target_info(CompilerInstance *Clang,
255 DiagnosticsEngine &Diags)
257 TargetOptions &TO = Clang->getTargetOpts();
258 TO.Triple = llvm::sys::getDefaultTargetTriple();
259 return TargetInfo::CreateTargetInfo(Diags, &TO);
262 #else
264 static TargetInfo *create_target_info(CompilerInstance *Clang,
265 DiagnosticsEngine &Diags)
267 TargetOptions &TO = Clang->getTargetOpts();
268 TO.Triple = llvm::sys::getDefaultTargetTriple();
269 return TargetInfo::CreateTargetInfo(Diags, TO);
272 #endif
274 #ifdef CREATEDIAGNOSTICS_TAKES_ARG
276 static void create_diagnostics(CompilerInstance *Clang)
278 Clang->createDiagnostics(0, NULL, construct_printer());
281 #else
283 static void create_diagnostics(CompilerInstance *Clang)
285 Clang->createDiagnostics(construct_printer());
288 #endif
290 #ifdef CREATEPREPROCESSOR_TAKES_TUKIND
292 static void create_preprocessor(CompilerInstance *Clang)
294 Clang->createPreprocessor(TU_Complete);
297 #else
299 static void create_preprocessor(CompilerInstance *Clang)
301 Clang->createPreprocessor();
304 #endif
306 #ifdef ADDPATH_TAKES_4_ARGUMENTS
308 void add_path(HeaderSearchOptions &HSO, string Path)
310 HSO.AddPath(Path, frontend::Angled, false, false);
313 #else
315 void add_path(HeaderSearchOptions &HSO, string Path)
317 HSO.AddPath(Path, frontend::Angled, true, false, false);
320 #endif
322 #ifdef HAVE_SETMAINFILEID
324 static void create_main_file_id(SourceManager &SM, const FileEntry *file)
326 SM.setMainFileID(SM.createFileID(file, SourceLocation(),
327 SrcMgr::C_User));
330 #else
332 static void create_main_file_id(SourceManager &SM, const FileEntry *file)
334 SM.createMainFileID(file);
337 #endif
339 int main(int argc, char *argv[])
341 llvm::cl::ParseCommandLineOptions(argc, argv);
343 CompilerInstance *Clang = new CompilerInstance();
344 create_diagnostics(Clang);
345 DiagnosticsEngine &Diags = Clang->getDiagnostics();
346 Diags.setSuppressSystemWarnings(true);
347 CompilerInvocation *invocation =
348 construct_invocation(InputFilename.c_str(), Diags);
349 if (invocation)
350 Clang->setInvocation(invocation);
351 Clang->createFileManager();
352 Clang->createSourceManager(Clang->getFileManager());
353 TargetInfo *target = create_target_info(Clang, Diags);
354 Clang->setTarget(target);
355 CompilerInvocation::setLangDefaults(Clang->getLangOpts(), IK_C,
356 LangStandard::lang_unspecified);
357 HeaderSearchOptions &HSO = Clang->getHeaderSearchOpts();
358 LangOptions &LO = Clang->getLangOpts();
359 PreprocessorOptions &PO = Clang->getPreprocessorOpts();
360 HSO.ResourceDir = ResourceDir;
362 for (int i = 0; i < Includes.size(); ++i)
363 add_path(HSO, Includes[i]);
365 PO.addMacroDef("__isl_give=__attribute__((annotate(\"isl_give\")))");
366 PO.addMacroDef("__isl_keep=__attribute__((annotate(\"isl_keep\")))");
367 PO.addMacroDef("__isl_take=__attribute__((annotate(\"isl_take\")))");
368 PO.addMacroDef("__isl_export=__attribute__((annotate(\"isl_export\")))");
369 PO.addMacroDef("__isl_constructor=__attribute__((annotate(\"isl_constructor\"))) __attribute__((annotate(\"isl_export\")))");
370 PO.addMacroDef("__isl_subclass(super)=__attribute__((annotate(\"isl_subclass(\" #super \")\"))) __attribute__((annotate(\"isl_export\")))");
372 create_preprocessor(Clang);
373 Preprocessor &PP = Clang->getPreprocessor();
375 PP.getBuiltinInfo().InitializeBuiltins(PP.getIdentifierTable(), LO);
377 const FileEntry *file = Clang->getFileManager().getFile(InputFilename);
378 assert(file);
379 create_main_file_id(Clang->getSourceManager(), file);
381 Clang->createASTContext();
382 MyASTConsumer consumer;
383 Sema *sema = new Sema(PP, Clang->getASTContext(), consumer);
385 Diags.getClient()->BeginSourceFile(LO, &PP);
386 ParseAST(*sema);
387 Diags.getClient()->EndSourceFile();
389 generate_python(consumer.types, consumer.functions);
391 delete sema;
392 delete Clang;
393 llvm::llvm_shutdown();
395 return 0;