pet_codegen.c: add missing include
[pet.git] / pet.cc
blob920e72e9ad360edeb2f5fbd1627bfabf9f438af3
1 /*
2 * Copyright 2011 Leiden University. All rights reserved.
3 * Copyright 2012-2014 Ecole Normale Superieure. All rights reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
7 * are met:
8 *
9 * 1. Redistributions of source code must retain the above copyright
10 * notice, this list of conditions and the following disclaimer.
12 * 2. Redistributions in binary form must reproduce the above
13 * copyright notice, this list of conditions and the following
14 * disclaimer in the documentation and/or other materials provided
15 * with the distribution.
17 * THIS SOFTWARE IS PROVIDED BY LEIDEN UNIVERSITY ''AS IS'' AND ANY
18 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
20 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL LEIDEN UNIVERSITY OR
21 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
22 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
23 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
24 * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
25 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
26 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
27 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29 * The views and conclusions contained in the software and documentation
30 * are those of the authors and should not be interpreted as
31 * representing official policies, either expressed or implied, of
32 * Leiden University.
33 */
35 #include "config.h"
37 #include <stdlib.h>
38 #include <map>
39 #include <vector>
40 #include <iostream>
41 #ifdef HAVE_ADT_OWNINGPTR_H
42 #include <llvm/ADT/OwningPtr.h>
43 #else
44 #include <memory>
45 #endif
46 #include <llvm/Support/raw_ostream.h>
47 #include <llvm/Support/ManagedStatic.h>
48 #include <llvm/Support/Host.h>
49 #include <clang/Basic/Version.h>
50 #include <clang/Basic/FileSystemOptions.h>
51 #include <clang/Basic/FileManager.h>
52 #include <clang/Basic/TargetOptions.h>
53 #include <clang/Basic/TargetInfo.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 #ifdef HAVE_LEX_HEADERSEARCHOPTIONS_H
66 #include <clang/Lex/HeaderSearchOptions.h>
67 #else
68 #include <clang/Frontend/HeaderSearchOptions.h>
69 #endif
70 #include <clang/Frontend/LangStandard.h>
71 #ifdef HAVE_LEX_PREPROCESSOROPTIONS_H
72 #include <clang/Lex/PreprocessorOptions.h>
73 #else
74 #include <clang/Frontend/PreprocessorOptions.h>
75 #endif
76 #include <clang/Frontend/FrontendOptions.h>
77 #include <clang/Frontend/Utils.h>
78 #include <clang/Lex/HeaderSearch.h>
79 #include <clang/Lex/Preprocessor.h>
80 #include <clang/Lex/Pragma.h>
81 #include <clang/AST/ASTContext.h>
82 #include <clang/AST/ASTConsumer.h>
83 #include <clang/Sema/Sema.h>
84 #include <clang/Sema/SemaDiagnostic.h>
85 #include <clang/Parse/Parser.h>
86 #include <clang/Parse/ParseAST.h>
88 #include <isl/ctx.h>
89 #include <isl/constraint.h>
91 #include <pet.h>
93 #include "id.h"
94 #include "options.h"
95 #include "scan.h"
96 #include "print.h"
98 #define ARRAY_SIZE(array) (sizeof(array)/sizeof(*array))
100 using namespace std;
101 using namespace clang;
102 using namespace clang::driver;
104 #ifdef HAVE_ADT_OWNINGPTR_H
105 #define unique_ptr llvm::OwningPtr
106 #endif
108 /* Called if we found something we didn't expect in one of the pragmas.
109 * We'll provide more informative warnings later.
111 static void unsupported(Preprocessor &PP, SourceLocation loc)
113 DiagnosticsEngine &diag = PP.getDiagnostics();
114 unsigned id = diag.getCustomDiagID(DiagnosticsEngine::Warning,
115 "unsupported");
116 DiagnosticBuilder B = diag.Report(loc, id);
119 static int get_int(const char *s)
121 return s[0] == '"' ? atoi(s + 1) : atoi(s);
124 static ValueDecl *get_value_decl(Sema &sema, Token &token)
126 IdentifierInfo *name;
127 Decl *decl;
129 if (token.isNot(tok::identifier))
130 return NULL;
132 name = token.getIdentifierInfo();
133 decl = sema.LookupSingleName(sema.TUScope, name,
134 token.getLocation(), Sema::LookupOrdinaryName);
135 return decl ? cast_or_null<ValueDecl>(decl) : NULL;
138 /* Handle pragmas of the form
140 * #pragma value_bounds identifier lower_bound upper_bound
142 * For each such pragma, add a mapping
143 * { identifier[] -> [i] : lower_bound <= i <= upper_bound }
144 * to value_bounds.
146 struct PragmaValueBoundsHandler : public PragmaHandler {
147 Sema &sema;
148 isl_ctx *ctx;
149 isl_union_map *value_bounds;
151 PragmaValueBoundsHandler(isl_ctx *ctx, Sema &sema) :
152 PragmaHandler("value_bounds"), sema(sema), ctx(ctx) {
153 isl_space *space = isl_space_params_alloc(ctx, 0);
154 value_bounds = isl_union_map_empty(space);
157 ~PragmaValueBoundsHandler() {
158 isl_union_map_free(value_bounds);
161 virtual void HandlePragma(Preprocessor &PP,
162 PragmaIntroducerKind Introducer,
163 Token &ScopTok) {
164 isl_id *id;
165 isl_space *dim;
166 isl_map *map;
167 ValueDecl *vd;
168 Token token;
169 int lb;
170 int ub;
172 PP.Lex(token);
173 vd = get_value_decl(sema, token);
174 if (!vd) {
175 unsupported(PP, token.getLocation());
176 return;
179 PP.Lex(token);
180 if (!token.isLiteral()) {
181 unsupported(PP, token.getLocation());
182 return;
185 lb = get_int(token.getLiteralData());
187 PP.Lex(token);
188 if (!token.isLiteral()) {
189 unsupported(PP, token.getLocation());
190 return;
193 ub = get_int(token.getLiteralData());
195 dim = isl_space_alloc(ctx, 0, 0, 1);
196 map = isl_map_universe(dim);
197 map = isl_map_lower_bound_si(map, isl_dim_out, 0, lb);
198 map = isl_map_upper_bound_si(map, isl_dim_out, 0, ub);
199 id = isl_id_alloc(ctx, vd->getName().str().c_str(), vd);
200 map = isl_map_set_tuple_id(map, isl_dim_in, id);
202 value_bounds = isl_union_map_add_map(value_bounds, map);
206 /* Given a variable declaration, check if it has an integer initializer
207 * and if so, add a parameter corresponding to the variable to "value"
208 * with its value fixed to the integer initializer and return the result.
210 static __isl_give isl_set *extract_initialization(__isl_take isl_set *value,
211 ValueDecl *decl)
213 VarDecl *vd;
214 Expr *expr;
215 IntegerLiteral *il;
216 isl_val *v;
217 isl_ctx *ctx;
218 isl_id *id;
219 isl_space *space;
220 isl_set *set;
222 vd = cast<VarDecl>(decl);
223 if (!vd)
224 return value;
225 if (!vd->getType()->isIntegerType())
226 return value;
227 expr = vd->getInit();
228 if (!expr)
229 return value;
230 il = cast<IntegerLiteral>(expr);
231 if (!il)
232 return value;
234 ctx = isl_set_get_ctx(value);
235 id = isl_id_alloc(ctx, vd->getName().str().c_str(), vd);
236 space = isl_space_params_alloc(ctx, 1);
237 space = isl_space_set_dim_id(space, isl_dim_param, 0, id);
238 set = isl_set_universe(space);
240 v = PetScan::extract_int(ctx, il);
241 set = isl_set_fix_val(set, isl_dim_param, 0, v);
243 return isl_set_intersect(value, set);
246 /* Handle pragmas of the form
248 * #pragma parameter identifier lower_bound
249 * and
250 * #pragma parameter identifier lower_bound upper_bound
252 * For each such pragma, intersect the context with the set
253 * [identifier] -> { [] : lower_bound <= identifier <= upper_bound }
255 struct PragmaParameterHandler : public PragmaHandler {
256 Sema &sema;
257 isl_set *&context;
258 isl_set *&context_value;
260 PragmaParameterHandler(Sema &sema, isl_set *&context,
261 isl_set *&context_value) :
262 PragmaHandler("parameter"), sema(sema), context(context),
263 context_value(context_value) {}
265 virtual void HandlePragma(Preprocessor &PP,
266 PragmaIntroducerKind Introducer,
267 Token &ScopTok) {
268 isl_id *id;
269 isl_ctx *ctx = isl_set_get_ctx(context);
270 isl_space *dim;
271 isl_set *set;
272 ValueDecl *vd;
273 Token token;
274 int lb;
275 int ub;
276 bool has_ub = false;
278 PP.Lex(token);
279 vd = get_value_decl(sema, token);
280 if (!vd) {
281 unsupported(PP, token.getLocation());
282 return;
285 PP.Lex(token);
286 if (!token.isLiteral()) {
287 unsupported(PP, token.getLocation());
288 return;
291 lb = get_int(token.getLiteralData());
293 PP.Lex(token);
294 if (token.isLiteral()) {
295 has_ub = true;
296 ub = get_int(token.getLiteralData());
297 } else if (token.isNot(tok::eod)) {
298 unsupported(PP, token.getLocation());
299 return;
302 id = isl_id_alloc(ctx, vd->getName().str().c_str(), vd);
303 dim = isl_space_params_alloc(ctx, 1);
304 dim = isl_space_set_dim_id(dim, isl_dim_param, 0, id);
306 set = isl_set_universe(dim);
308 set = isl_set_lower_bound_si(set, isl_dim_param, 0, lb);
309 if (has_ub)
310 set = isl_set_upper_bound_si(set, isl_dim_param, 0, ub);
312 context = isl_set_intersect(context, set);
314 context_value = extract_initialization(context_value, vd);
318 /* Handle pragmas of the form
320 * #pragma pencil independent
322 * For each such pragma, add an entry to the "independent" vector.
324 struct PragmaPencilHandler : public PragmaHandler {
325 std::vector<Independent> &independent;
327 PragmaPencilHandler(std::vector<Independent> &independent) :
328 PragmaHandler("pencil"), independent(independent) {}
330 virtual void HandlePragma(Preprocessor &PP,
331 PragmaIntroducerKind Introducer,
332 Token &PencilTok) {
333 Token token;
334 IdentifierInfo *info;
336 PP.Lex(token);
337 if (token.isNot(tok::identifier))
338 return;
340 info = token.getIdentifierInfo();
341 if (!info->isStr("independent"))
342 return;
344 PP.Lex(token);
345 if (token.isNot(tok::eod))
346 return;
348 SourceManager &SM = PP.getSourceManager();
349 SourceLocation sloc = PencilTok.getLocation();
350 unsigned line = SM.getExpansionLineNumber(sloc);
351 independent.push_back(Independent(line));
355 #ifdef HAVE_TRANSLATELINECOL
357 /* Return a SourceLocation for line "line", column "col" of file "FID".
359 SourceLocation translateLineCol(SourceManager &SM, FileID FID, unsigned line,
360 unsigned col)
362 return SM.translateLineCol(FID, line, col);
365 #else
367 /* Return a SourceLocation for line "line", column "col" of file "FID".
369 SourceLocation translateLineCol(SourceManager &SM, FileID FID, unsigned line,
370 unsigned col)
372 return SM.getLocation(SM.getFileEntryForID(FID), line, col);
375 #endif
377 /* List of pairs of #pragma scop and #pragma endscop locations.
379 struct ScopLocList {
380 std::vector<ScopLoc> list;
382 /* Add a new start (#pragma scop) location to the list.
383 * If the last #pragma scop did not have a matching
384 * #pragma endscop then overwrite it.
385 * "start" points to the location of the scop pragma.
387 void add_start(SourceManager &SM, SourceLocation start) {
388 ScopLoc loc;
390 loc.scop = start;
391 int line = SM.getExpansionLineNumber(start);
392 start = translateLineCol(SM, SM.getFileID(start), line, 1);
393 loc.start_line = line;
394 loc.start = SM.getFileOffset(start);
395 if (list.size() == 0 || list[list.size() - 1].end != 0)
396 list.push_back(loc);
397 else
398 list[list.size() - 1] = loc;
401 /* Set the end location (#pragma endscop) of the last pair
402 * in the list.
403 * If there is no such pair of if the end of that pair
404 * is already set, then ignore the spurious #pragma endscop.
405 * "end" points to the location of the endscop pragma.
407 void add_end(SourceManager &SM, SourceLocation end) {
408 if (list.size() == 0 || list[list.size() - 1].end != 0)
409 return;
410 list[list.size() - 1].endscop = end;
411 int line = SM.getExpansionLineNumber(end);
412 end = translateLineCol(SM, SM.getFileID(end), line + 1, 1);
413 list[list.size() - 1].end = SM.getFileOffset(end);
417 /* Handle pragmas of the form
419 * #pragma scop
421 * In particular, store the location of the line containing
422 * the pragma in the list "scops".
424 struct PragmaScopHandler : public PragmaHandler {
425 ScopLocList &scops;
427 PragmaScopHandler(ScopLocList &scops) :
428 PragmaHandler("scop"), scops(scops) {}
430 virtual void HandlePragma(Preprocessor &PP,
431 PragmaIntroducerKind Introducer,
432 Token &ScopTok) {
433 SourceManager &SM = PP.getSourceManager();
434 SourceLocation sloc = ScopTok.getLocation();
435 scops.add_start(SM, sloc);
439 /* Handle pragmas of the form
441 * #pragma endscop
443 * In particular, store the location of the line following the one containing
444 * the pragma in the list "scops".
446 struct PragmaEndScopHandler : public PragmaHandler {
447 ScopLocList &scops;
449 PragmaEndScopHandler(ScopLocList &scops) :
450 PragmaHandler("endscop"), scops(scops) {}
452 virtual void HandlePragma(Preprocessor &PP,
453 PragmaIntroducerKind Introducer,
454 Token &EndScopTok) {
455 SourceManager &SM = PP.getSourceManager();
456 SourceLocation sloc = EndScopTok.getLocation();
457 scops.add_end(SM, sloc);
461 /* Handle pragmas of the form
463 * #pragma live-out identifier, identifier, ...
465 * Each identifier on the line is stored in live_out.
467 struct PragmaLiveOutHandler : public PragmaHandler {
468 Sema &sema;
469 set<ValueDecl *> &live_out;
471 PragmaLiveOutHandler(Sema &sema, set<ValueDecl *> &live_out) :
472 PragmaHandler("live"), sema(sema), live_out(live_out) {}
474 virtual void HandlePragma(Preprocessor &PP,
475 PragmaIntroducerKind Introducer,
476 Token &ScopTok) {
477 Token token;
479 PP.Lex(token);
480 if (token.isNot(tok::minus))
481 return;
482 PP.Lex(token);
483 if (token.isNot(tok::identifier) ||
484 !token.getIdentifierInfo()->isStr("out"))
485 return;
487 PP.Lex(token);
488 while (token.isNot(tok::eod)) {
489 ValueDecl *vd;
491 vd = get_value_decl(sema, token);
492 if (!vd) {
493 unsupported(PP, token.getLocation());
494 return;
496 live_out.insert(vd);
497 PP.Lex(token);
498 if (token.is(tok::comma))
499 PP.Lex(token);
504 /* For each array in "scop", set its value_bounds property
505 * based on the information in "value_bounds" and
506 * mark it as live_out if it appears in "live_out".
508 static void update_arrays(struct pet_scop *scop,
509 __isl_take isl_union_map *value_bounds, set<ValueDecl *> &live_out)
511 set<ValueDecl *>::iterator lo_it;
512 isl_ctx *ctx = isl_union_map_get_ctx(value_bounds);
514 if (!scop) {
515 isl_union_map_free(value_bounds);
516 return;
519 for (int i = 0; i < scop->n_array; ++i) {
520 isl_id *id;
521 isl_space *space;
522 isl_map *bounds;
523 ValueDecl *decl;
524 pet_array *array = scop->arrays[i];
526 id = isl_set_get_tuple_id(array->extent);
527 decl = pet_id_get_decl(id);
529 space = isl_space_alloc(ctx, 0, 0, 1);
530 space = isl_space_set_tuple_id(space, isl_dim_in, id);
532 bounds = isl_union_map_extract_map(value_bounds, space);
533 if (!isl_map_plain_is_empty(bounds))
534 array->value_bounds = isl_map_range(bounds);
535 else
536 isl_map_free(bounds);
538 lo_it = live_out.find(decl);
539 if (lo_it != live_out.end())
540 array->live_out = 1;
543 isl_union_map_free(value_bounds);
546 /* Extract a pet_scop (if any) from each appropriate function.
547 * Each detected scop is passed to "fn".
548 * When autodetecting, at most one scop is extracted from each function.
549 * If "function" is not NULL, then we only extract a pet_scop if the
550 * name of the function matches.
551 * If "autodetect" is false, then we only extract if we have seen
552 * scop and endscop pragmas and if these are situated inside the function
553 * body.
555 struct PetASTConsumer : public ASTConsumer {
556 Preprocessor &PP;
557 ASTContext &ast_context;
558 DiagnosticsEngine &diags;
559 ScopLocList &scops;
560 std::vector<Independent> independent;
561 const char *function;
562 pet_options *options;
563 isl_ctx *ctx;
564 isl_set *context;
565 isl_set *context_value;
566 set<ValueDecl *> live_out;
567 PragmaValueBoundsHandler *vb_handler;
568 int (*fn)(struct pet_scop *scop, void *user);
569 void *user;
570 bool error;
572 PetASTConsumer(isl_ctx *ctx, Preprocessor &PP, ASTContext &ast_context,
573 DiagnosticsEngine &diags, ScopLocList &scops,
574 const char *function, pet_options *options,
575 int (*fn)(struct pet_scop *scop, void *user), void *user) :
576 PP(PP), ast_context(ast_context), diags(diags),
577 scops(scops), function(function), options(options),
578 ctx(ctx),
579 vb_handler(NULL), fn(fn), user(user), error(false)
581 isl_space *space;
582 space = isl_space_params_alloc(ctx, 0);
583 context = isl_set_universe(isl_space_copy(space));
584 context_value = isl_set_universe(space);
587 ~PetASTConsumer() {
588 isl_set_free(context);
589 isl_set_free(context_value);
592 void handle_value_bounds(Sema *sema) {
593 vb_handler = new PragmaValueBoundsHandler(ctx, *sema);
594 PP.AddPragmaHandler(vb_handler);
597 /* Add all pragma handlers to this->PP.
598 * The pencil pragmas are only handled if the pencil option is set.
600 void add_pragma_handlers(Sema *sema) {
601 PP.AddPragmaHandler(new PragmaParameterHandler(*sema, context,
602 context_value));
603 if (options->pencil) {
604 PragmaHandler *PH;
605 PH = new PragmaPencilHandler(independent);
606 PP.AddPragmaHandler(PH);
608 handle_value_bounds(sema);
611 __isl_give isl_union_map *get_value_bounds() {
612 return isl_union_map_copy(vb_handler->value_bounds);
615 /* Pass "scop" to "fn" after performing some postprocessing.
616 * In particular, add the context and value_bounds constraints
617 * speficied through pragmas, add reference identifiers and
618 * reset user pointers on parameters and tuple ids.
620 * If "scop" does not contain any statements and autodetect
621 * is turned on, then skip it.
623 void call_fn(pet_scop *scop) {
624 if (!scop)
625 return;
626 if (diags.hasErrorOccurred()) {
627 pet_scop_free(scop);
628 return;
630 if (options->autodetect && scop->n_stmt == 0) {
631 pet_scop_free(scop);
632 return;
634 scop->context = isl_set_intersect(scop->context,
635 isl_set_copy(context));
636 scop->context_value = isl_set_intersect(scop->context_value,
637 isl_set_copy(context_value));
639 update_arrays(scop, get_value_bounds(), live_out);
641 scop = pet_scop_add_ref_ids(scop);
642 scop = pet_scop_anonymize(scop);
644 if (fn(scop, user) < 0)
645 error = true;
648 /* For each explicitly marked scop (using pragmas),
649 * extract the scop and call "fn" on it if it is inside "fd".
651 void scan_scops(FunctionDecl *fd) {
652 unsigned start, end;
653 vector<ScopLoc>::iterator it;
654 isl_union_map *vb = vb_handler->value_bounds;
655 SourceManager &SM = PP.getSourceManager();
656 pet_scop *scop;
658 if (scops.list.size() == 0)
659 return;
661 start = SM.getFileOffset(fd->getLocStart());
662 end = SM.getFileOffset(fd->getLocEnd());
664 for (it = scops.list.begin(); it != scops.list.end(); ++it) {
665 ScopLoc loc = *it;
666 if (!loc.end)
667 continue;
668 if (start > loc.end)
669 continue;
670 if (end < loc.start)
671 continue;
672 PetScan ps(PP, ast_context, fd, loc, options,
673 isl_union_map_copy(vb), independent);
674 scop = ps.scan(fd);
675 call_fn(scop);
679 virtual HandleTopLevelDeclReturn HandleTopLevelDecl(DeclGroupRef dg) {
680 DeclGroupRef::iterator it;
682 if (error)
683 return HandleTopLevelDeclContinue;
685 for (it = dg.begin(); it != dg.end(); ++it) {
686 isl_union_map *vb = vb_handler->value_bounds;
687 FunctionDecl *fd = dyn_cast<clang::FunctionDecl>(*it);
688 if (!fd)
689 continue;
690 if (!fd->hasBody())
691 continue;
692 if (function &&
693 fd->getNameInfo().getAsString() != function)
694 continue;
695 if (options->autodetect) {
696 ScopLoc loc;
697 pet_scop *scop;
698 PetScan ps(PP, ast_context, fd, loc, options,
699 isl_union_map_copy(vb),
700 independent);
701 scop = ps.scan(fd);
702 call_fn(scop);
703 continue;
705 scan_scops(fd);
708 return HandleTopLevelDeclContinue;
712 static const char *ResourceDir =
713 CLANG_PREFIX "/lib/clang/" CLANG_VERSION_STRING;
715 static const char *implicit_functions[] = {
716 "min", "max", "intMod", "intCeil", "intFloor", "ceild", "floord"
718 static const char *pencil_implicit_functions[] = {
719 "imin", "umin", "imax", "umax", "__pencil_kill"
722 /* Should "ident" be treated as an implicit function?
723 * If "pencil" is set, then also allow pencil specific builtins.
725 static bool is_implicit(const IdentifierInfo *ident, int pencil)
727 const char *name = ident->getNameStart();
728 for (size_t i = 0; i < ARRAY_SIZE(implicit_functions); ++i)
729 if (!strcmp(name, implicit_functions[i]))
730 return true;
731 if (!pencil)
732 return false;
733 for (size_t i = 0; i < ARRAY_SIZE(pencil_implicit_functions); ++i)
734 if (!strcmp(name, pencil_implicit_functions[i]))
735 return true;
736 return false;
739 /* Ignore implicit function declaration warnings on
740 * "min", "max", "ceild" and "floord" as we detect and handle these
741 * in PetScan.
742 * If "pencil" is set, then also ignore them on pencil specific
743 * builtins.
745 struct MyDiagnosticPrinter : public TextDiagnosticPrinter {
746 const DiagnosticOptions *DiagOpts;
747 int pencil;
748 #ifdef HAVE_BASIC_DIAGNOSTICOPTIONS_H
749 MyDiagnosticPrinter(DiagnosticOptions *DO, int pencil) :
750 TextDiagnosticPrinter(llvm::errs(), DO), pencil(pencil) {}
751 virtual DiagnosticConsumer *clone(DiagnosticsEngine &Diags) const {
752 return new MyDiagnosticPrinter(&Diags.getDiagnosticOptions(),
753 pencil);
755 #else
756 MyDiagnosticPrinter(const DiagnosticOptions &DO, int pencil) :
757 DiagOpts(&DO), TextDiagnosticPrinter(llvm::errs(), DO),
758 pencil(pencil) {}
759 virtual DiagnosticConsumer *clone(DiagnosticsEngine &Diags) const {
760 return new MyDiagnosticPrinter(*DiagOpts, pencil);
762 #endif
763 virtual void HandleDiagnostic(DiagnosticsEngine::Level level,
764 const DiagnosticInfo &info) {
765 if (info.getID() == diag::ext_implicit_function_decl &&
766 info.getNumArgs() == 1 &&
767 info.getArgKind(0) == DiagnosticsEngine::ak_identifierinfo &&
768 is_implicit(info.getArgIdentifier(0), pencil))
769 /* ignore warning */;
770 else
771 TextDiagnosticPrinter::HandleDiagnostic(level, info);
775 #ifdef USE_ARRAYREF
777 #ifdef HAVE_CXXISPRODUCTION
778 static Driver *construct_driver(const char *binary, DiagnosticsEngine &Diags)
780 return new Driver(binary, llvm::sys::getDefaultTargetTriple(),
781 "", false, false, Diags);
783 #elif defined(HAVE_ISPRODUCTION)
784 static Driver *construct_driver(const char *binary, DiagnosticsEngine &Diags)
786 return new Driver(binary, llvm::sys::getDefaultTargetTriple(),
787 "", false, Diags);
789 #elif defined(DRIVER_CTOR_TAKES_DEFAULTIMAGENAME)
790 static Driver *construct_driver(const char *binary, DiagnosticsEngine &Diags)
792 return new Driver(binary, llvm::sys::getDefaultTargetTriple(),
793 "", Diags);
795 #else
796 static Driver *construct_driver(const char *binary, DiagnosticsEngine &Diags)
798 return new Driver(binary, llvm::sys::getDefaultTargetTriple(), Diags);
800 #endif
802 namespace clang { namespace driver { class Job; } }
804 /* Clang changed its API from 3.5 to 3.6 and once more in 3.7.
805 * We fix this with a simple overloaded function here.
807 struct ClangAPI {
808 static Job *command(Job *J) { return J; }
809 static Job *command(Job &J) { return &J; }
810 static Command *command(Command &C) { return &C; }
813 /* Create a CompilerInvocation object that stores the command line
814 * arguments constructed by the driver.
815 * The arguments are mainly useful for setting up the system include
816 * paths on newer clangs and on some platforms.
818 static CompilerInvocation *construct_invocation(const char *filename,
819 DiagnosticsEngine &Diags)
821 const char *binary = CLANG_PREFIX"/bin/clang";
822 const unique_ptr<Driver> driver(construct_driver(binary, Diags));
823 std::vector<const char *> Argv;
824 Argv.push_back(binary);
825 Argv.push_back(filename);
826 const unique_ptr<Compilation> compilation(
827 driver->BuildCompilation(llvm::ArrayRef<const char *>(Argv)));
828 JobList &Jobs = compilation->getJobs();
829 if (Jobs.size() < 1)
830 return NULL;
832 Command *cmd = cast<Command>(ClangAPI::command(*Jobs.begin()));
833 if (strcmp(cmd->getCreator().getName(), "clang"))
834 return NULL;
836 const ArgStringList *args = &cmd->getArguments();
838 CompilerInvocation *invocation = new CompilerInvocation;
839 CompilerInvocation::CreateFromArgs(*invocation, args->data() + 1,
840 args->data() + args->size(),
841 Diags);
842 return invocation;
845 #else
847 static CompilerInvocation *construct_invocation(const char *filename,
848 DiagnosticsEngine &Diags)
850 return NULL;
853 #endif
855 #ifdef HAVE_BASIC_DIAGNOSTICOPTIONS_H
857 static MyDiagnosticPrinter *construct_printer(CompilerInstance *Clang,
858 int pencil)
860 return new MyDiagnosticPrinter(new DiagnosticOptions(), pencil);
863 #else
865 static MyDiagnosticPrinter *construct_printer(CompilerInstance *Clang,
866 int pencil)
868 return new MyDiagnosticPrinter(Clang->getDiagnosticOpts(), pencil);
871 #endif
873 #ifdef CREATETARGETINFO_TAKES_SHARED_PTR
875 static TargetInfo *create_target_info(CompilerInstance *Clang,
876 DiagnosticsEngine &Diags)
878 shared_ptr<TargetOptions> TO = Clang->getInvocation().TargetOpts;
879 TO->Triple = llvm::sys::getDefaultTargetTriple();
880 return TargetInfo::CreateTargetInfo(Diags, TO);
883 #elif defined(CREATETARGETINFO_TAKES_POINTER)
885 static TargetInfo *create_target_info(CompilerInstance *Clang,
886 DiagnosticsEngine &Diags)
888 TargetOptions &TO = Clang->getTargetOpts();
889 TO.Triple = llvm::sys::getDefaultTargetTriple();
890 return TargetInfo::CreateTargetInfo(Diags, &TO);
893 #else
895 static TargetInfo *create_target_info(CompilerInstance *Clang,
896 DiagnosticsEngine &Diags)
898 TargetOptions &TO = Clang->getTargetOpts();
899 TO.Triple = llvm::sys::getDefaultTargetTriple();
900 return TargetInfo::CreateTargetInfo(Diags, TO);
903 #endif
905 #ifdef CREATEDIAGNOSTICS_TAKES_ARG
907 static void create_diagnostics(CompilerInstance *Clang)
909 Clang->createDiagnostics(0, NULL);
912 #else
914 static void create_diagnostics(CompilerInstance *Clang)
916 Clang->createDiagnostics();
919 #endif
921 #ifdef CREATEPREPROCESSOR_TAKES_TUKIND
923 static void create_preprocessor(CompilerInstance *Clang)
925 Clang->createPreprocessor(TU_Complete);
928 #else
930 static void create_preprocessor(CompilerInstance *Clang)
932 Clang->createPreprocessor();
935 #endif
937 #ifdef ADDPATH_TAKES_4_ARGUMENTS
939 void add_path(HeaderSearchOptions &HSO, string Path)
941 HSO.AddPath(Path, frontend::Angled, false, false);
944 #else
946 void add_path(HeaderSearchOptions &HSO, string Path)
948 HSO.AddPath(Path, frontend::Angled, true, false, false);
951 #endif
953 #ifdef HAVE_SETMAINFILEID
955 static void create_main_file_id(SourceManager &SM, const FileEntry *file)
957 SM.setMainFileID(SM.createFileID(file, SourceLocation(),
958 SrcMgr::C_User));
961 #else
963 static void create_main_file_id(SourceManager &SM, const FileEntry *file)
965 SM.createMainFileID(file);
968 #endif
970 #ifdef SETLANGDEFAULTS_TAKES_5_ARGUMENTS
972 static void set_lang_defaults(CompilerInstance *Clang)
974 PreprocessorOptions &PO = Clang->getPreprocessorOpts();
975 TargetOptions &TO = Clang->getTargetOpts();
976 llvm::Triple T(TO.Triple);
977 CompilerInvocation::setLangDefaults(Clang->getLangOpts(), IK_C, T, PO,
978 LangStandard::lang_unspecified);
981 #else
983 static void set_lang_defaults(CompilerInstance *Clang)
985 CompilerInvocation::setLangDefaults(Clang->getLangOpts(), IK_C,
986 LangStandard::lang_unspecified);
989 #endif
991 #ifdef SETINVOCATION_TAKES_SHARED_PTR
993 static void set_invocation(CompilerInstance *Clang,
994 CompilerInvocation *invocation)
996 Clang->setInvocation(std::shared_ptr<CompilerInvocation>(invocation));
999 #else
1001 static void set_invocation(CompilerInstance *Clang,
1002 CompilerInvocation *invocation)
1004 Clang->setInvocation(invocation);
1007 #endif
1009 /* Add pet specific predefines to the preprocessor.
1010 * Currently, these are all pencil specific, so they are only
1011 * added if "pencil" is set.
1013 * We mimic the way <command line> is handled inside clang.
1015 void add_predefines(Preprocessor &PP, int pencil)
1017 string s;
1019 if (!pencil)
1020 return;
1022 s = PP.getPredefines();
1023 s += "# 1 \"<pet>\" 1\n"
1024 "void __pencil_assume(int assumption);\n"
1025 "#define pencil_access(f) annotate(\"pencil_access(\" #f \")\")\n"
1026 "# 1 \"<built-in>\" 2\n";
1027 PP.setPredefines(s);
1030 /* Extract a pet_scop from each function in the C source file called "filename".
1031 * Each detected scop is passed to "fn".
1032 * If "function" is not NULL, only extract a pet_scop from the function
1033 * with that name.
1034 * If "autodetect" is set, extract any pet_scop we can find.
1035 * Otherwise, extract the pet_scop from the region delimited
1036 * by "scop" and "endscop" pragmas.
1038 * We first set up the clang parser and then try to extract the
1039 * pet_scop from the appropriate function(s) in PetASTConsumer.
1041 static int foreach_scop_in_C_source(isl_ctx *ctx,
1042 const char *filename, const char *function, pet_options *options,
1043 int (*fn)(struct pet_scop *scop, void *user), void *user)
1045 CompilerInstance *Clang = new CompilerInstance();
1046 create_diagnostics(Clang);
1047 DiagnosticsEngine &Diags = Clang->getDiagnostics();
1048 Diags.setSuppressSystemWarnings(true);
1049 CompilerInvocation *invocation = construct_invocation(filename, Diags);
1050 if (invocation)
1051 set_invocation(Clang, invocation);
1052 Diags.setClient(construct_printer(Clang, options->pencil));
1053 Clang->createFileManager();
1054 Clang->createSourceManager(Clang->getFileManager());
1055 TargetInfo *target = create_target_info(Clang, Diags);
1056 Clang->setTarget(target);
1057 set_lang_defaults(Clang);
1058 HeaderSearchOptions &HSO = Clang->getHeaderSearchOpts();
1059 HSO.ResourceDir = ResourceDir;
1060 for (int i = 0; i < options->n_path; ++i)
1061 add_path(HSO, options->paths[i]);
1062 PreprocessorOptions &PO = Clang->getPreprocessorOpts();
1063 for (int i = 0; i < options->n_define; ++i)
1064 PO.addMacroDef(options->defines[i]);
1065 create_preprocessor(Clang);
1066 Preprocessor &PP = Clang->getPreprocessor();
1067 add_predefines(PP, options->pencil);
1068 PP.getBuiltinInfo().initializeBuiltins(PP.getIdentifierTable(),
1069 PP.getLangOpts());
1071 ScopLocList scops;
1073 const FileEntry *file = Clang->getFileManager().getFile(filename);
1074 if (!file)
1075 isl_die(ctx, isl_error_unknown, "unable to open file",
1076 do { delete Clang; return -1; } while (0));
1077 create_main_file_id(Clang->getSourceManager(), file);
1079 Clang->createASTContext();
1080 PetASTConsumer consumer(ctx, PP, Clang->getASTContext(), Diags,
1081 scops, function, options, fn, user);
1082 Sema *sema = new Sema(PP, Clang->getASTContext(), consumer);
1084 if (!options->autodetect) {
1085 PP.AddPragmaHandler(new PragmaScopHandler(scops));
1086 PP.AddPragmaHandler(new PragmaEndScopHandler(scops));
1087 PP.AddPragmaHandler(new PragmaLiveOutHandler(*sema,
1088 consumer.live_out));
1091 consumer.add_pragma_handlers(sema);
1093 Diags.getClient()->BeginSourceFile(Clang->getLangOpts(), &PP);
1094 ParseAST(*sema);
1095 Diags.getClient()->EndSourceFile();
1097 delete sema;
1098 delete Clang;
1100 return consumer.error ? -1 : 0;
1103 /* Extract a pet_scop from each function in the C source file called "filename".
1104 * Each detected scop is passed to "fn".
1106 * This wrapper around foreach_scop_in_C_source is mainly used to ensure
1107 * that all objects on the stack (of that function) are destroyed before we
1108 * call llvm_shutdown.
1110 static int pet_foreach_scop_in_C_source(isl_ctx *ctx,
1111 const char *filename, const char *function,
1112 int (*fn)(struct pet_scop *scop, void *user), void *user)
1114 int r;
1115 pet_options *options;
1116 bool allocated = false;
1118 options = isl_ctx_peek_pet_options(ctx);
1119 if (!options) {
1120 options = pet_options_new_with_defaults();
1121 allocated = true;
1124 r = foreach_scop_in_C_source(ctx, filename, function, options,
1125 fn, user);
1126 llvm::llvm_shutdown();
1128 if (allocated)
1129 pet_options_free(options);
1131 return r;
1134 /* Store "scop" into the address pointed to by "user".
1135 * Return -1 to indicate that we are not interested in any further scops.
1136 * This function should therefore not be called a second call
1137 * so in principle there is no need to check if we have already set *user.
1139 static int set_first_scop(pet_scop *scop, void *user)
1141 pet_scop **p = (pet_scop **) user;
1143 if (!*p)
1144 *p = scop;
1145 else
1146 pet_scop_free(scop);
1148 return -1;
1151 /* Extract a pet_scop from the C source file called "filename".
1152 * If "function" is not NULL, extract the pet_scop from the function
1153 * with that name.
1155 * We start extracting scops from every function and then abort
1156 * as soon as we have extracted one scop.
1158 struct pet_scop *pet_scop_extract_from_C_source(isl_ctx *ctx,
1159 const char *filename, const char *function)
1161 pet_scop *scop = NULL;
1163 pet_foreach_scop_in_C_source(ctx, filename, function,
1164 &set_first_scop, &scop);
1166 return scop;
1169 /* Internal data structure for pet_transform_C_source
1171 * transform is the function that should be called to print a scop
1172 * in is the input source file
1173 * out is the output source file
1174 * end is the offset of the end of the previous scop (zero if we have not
1175 * found any scop yet)
1176 * p is a printer that prints to out.
1178 struct pet_transform_data {
1179 __isl_give isl_printer *(*transform)(__isl_take isl_printer *p,
1180 struct pet_scop *scop, void *user);
1181 void *user;
1183 FILE *in;
1184 FILE *out;
1185 unsigned end;
1186 isl_printer *p;
1189 /* This function is called each time a scop is detected.
1191 * We first copy the input text code from the end of the previous scop
1192 * until the start of "scop" and then print the scop itself through
1193 * a call to data->transform. We set up the printer to print
1194 * the transformed code with the same (initial) indentation as
1195 * the original code.
1196 * Finally, we keep track of the end of "scop" so that we can
1197 * continue copying when we find the next scop.
1199 * Before calling data->transform, we store a pointer to the original
1200 * input file in the extended scop in case the user wants to call
1201 * pet_scop_print_original from the callback.
1203 static int pet_transform(struct pet_scop *scop, void *user)
1205 struct pet_transform_data *data = (struct pet_transform_data *) user;
1206 unsigned start;
1208 start = pet_loc_get_start(scop->loc);
1209 if (copy(data->in, data->out, data->end, start) < 0)
1210 goto error;
1211 data->end = pet_loc_get_end(scop->loc);
1212 scop = pet_scop_set_input_file(scop, data->in);
1213 data->p = isl_printer_set_indent_prefix(data->p,
1214 pet_loc_get_indent(scop->loc));
1215 data->p = data->transform(data->p, scop, data->user);
1216 if (!data->p)
1217 return -1;
1218 return 0;
1219 error:
1220 pet_scop_free(scop);
1221 return -1;
1224 /* Transform the C source file "input" by rewriting each scop
1225 * through a call to "transform".
1226 * When autodetecting scops, at most one scop per function is rewritten.
1227 * The transformed C code is written to "output".
1229 * For each scop we find, we first copy the input text code
1230 * from the end of the previous scop (or the beginning of the file
1231 * in case of the first scop) until the start of the scop
1232 * and then print the scop itself through a call to "transform".
1233 * At the end we copy everything from the end of the final scop
1234 * until the end of the input file to "output".
1236 int pet_transform_C_source(isl_ctx *ctx, const char *input, FILE *out,
1237 __isl_give isl_printer *(*transform)(__isl_take isl_printer *p,
1238 struct pet_scop *scop, void *user), void *user)
1240 struct pet_transform_data data;
1241 int r;
1243 data.in = stdin;
1244 data.out = out;
1245 if (input && strcmp(input, "-")) {
1246 data.in = fopen(input, "r");
1247 if (!data.in)
1248 isl_die(ctx, isl_error_unknown, "unable to open file",
1249 return -1);
1252 data.p = isl_printer_to_file(ctx, data.out);
1253 data.p = isl_printer_set_output_format(data.p, ISL_FORMAT_C);
1255 data.transform = transform;
1256 data.user = user;
1257 data.end = 0;
1258 r = pet_foreach_scop_in_C_source(ctx, input, NULL,
1259 &pet_transform, &data);
1261 isl_printer_free(data.p);
1262 if (!data.p)
1263 r = -1;
1264 if (r == 0 && copy(data.in, data.out, data.end, -1) < 0)
1265 r = -1;
1267 if (data.in != stdin)
1268 fclose(data.in);
1270 return r;