use isl_set_{lower,upper}_bound_si instead of our own open coded version
[pet.git] / pet.cc
blobbe31ffce57f4ada0fe7146a7faff6af1d5490e4f
1 /*
2 * Copyright 2011 Leiden University. 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 LEIDEN UNIVERSITY ''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 LEIDEN UNIVERSITY 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 * Leiden University.
32 */
34 #include <stdlib.h>
35 #include <map>
36 #include <iostream>
37 #include <llvm/Support/raw_ostream.h>
38 #include <llvm/Support/ManagedStatic.h>
39 #include <llvm/Support/Host.h>
40 #include <clang/Basic/Version.h>
41 #include <clang/Basic/FileSystemOptions.h>
42 #include <clang/Basic/FileManager.h>
43 #include <clang/Basic/TargetOptions.h>
44 #include <clang/Basic/TargetInfo.h>
45 #include <clang/Frontend/CompilerInstance.h>
46 #include <clang/Frontend/CompilerInvocation.h>
47 #include <clang/Frontend/DiagnosticOptions.h>
48 #include <clang/Frontend/TextDiagnosticPrinter.h>
49 #include <clang/Frontend/HeaderSearchOptions.h>
50 #include <clang/Frontend/LangStandard.h>
51 #include <clang/Frontend/PreprocessorOptions.h>
52 #include <clang/Frontend/FrontendOptions.h>
53 #include <clang/Frontend/Utils.h>
54 #include <clang/Lex/HeaderSearch.h>
55 #include <clang/Lex/Preprocessor.h>
56 #include <clang/Lex/Pragma.h>
57 #include <clang/AST/ASTContext.h>
58 #include <clang/AST/ASTConsumer.h>
59 #include <clang/Sema/Sema.h>
60 #include <clang/Sema/SemaDiagnostic.h>
61 #include <clang/Parse/Parser.h>
62 #include <clang/Parse/ParseAST.h>
64 #include <isl/ctx.h>
65 #include <isl/constraint.h>
67 #include "scan.h"
69 #include "config.h"
71 #define ARRAY_SIZE(array) (sizeof(array)/sizeof(*array))
73 using namespace std;
74 using namespace clang;
76 /* Called if we found something we didn't expect in one of the pragmas.
77 * We'll provide more informative warnings later.
79 static void unsupported(Preprocessor &PP, SourceLocation loc)
81 DiagnosticsEngine &diag = PP.getDiagnostics();
82 unsigned id = diag.getCustomDiagID(DiagnosticsEngine::Warning,
83 "unsupported");
84 DiagnosticBuilder B = diag.Report(loc, id);
87 static int get_int(const char *s)
89 return s[0] == '"' ? atoi(s + 1) : atoi(s);
92 static ValueDecl *get_value_decl(Sema &sema, Token &token)
94 IdentifierInfo *name;
95 Decl *decl;
97 if (token.isNot(tok::identifier))
98 return NULL;
100 name = token.getIdentifierInfo();
101 decl = sema.LookupSingleName(sema.TUScope, name,
102 token.getLocation(), Sema::LookupOrdinaryName);
103 return decl ? cast_or_null<ValueDecl>(decl) : NULL;
106 /* Handle pragmas of the form
108 * #pragma value_bounds identifier lower_bound upper_bound
110 * For each such pragma, add a mapping from the ValueDecl corresponding
111 * to "identifier" to a set { [i] : lower_bound <= i <= upper_bound }
112 * to the map value_bounds.
114 struct PragmaValueBoundsHandler : public PragmaHandler {
115 Sema &sema;
116 isl_ctx *ctx;
117 map<ValueDecl *, isl_set *> &value_bounds;
119 PragmaValueBoundsHandler(isl_ctx *ctx, Sema &sema,
120 map<ValueDecl *, isl_set *> &value_bounds) :
121 PragmaHandler("value_bounds"), ctx(ctx), sema(sema),
122 value_bounds(value_bounds) {}
124 virtual void HandlePragma(Preprocessor &PP,
125 PragmaIntroducerKind Introducer,
126 Token &ScopTok) {
127 isl_space *dim;
128 isl_set *set;
129 ValueDecl *vd;
130 Token token;
131 int lb;
132 int ub;
134 PP.Lex(token);
135 vd = get_value_decl(sema, token);
136 if (!vd) {
137 unsupported(PP, token.getLocation());
138 return;
141 PP.Lex(token);
142 if (!token.isLiteral()) {
143 unsupported(PP, token.getLocation());
144 return;
147 lb = get_int(token.getLiteralData());
149 PP.Lex(token);
150 if (!token.isLiteral()) {
151 unsupported(PP, token.getLocation());
152 return;
155 ub = get_int(token.getLiteralData());
157 dim = isl_space_set_alloc(ctx, 0, 1);
158 set = isl_set_universe(dim);
159 set = isl_set_lower_bound_si(set, isl_dim_set, 0, lb);
160 set = isl_set_upper_bound_si(set, isl_dim_set, 0, ub);
162 value_bounds[vd] = set;
166 /* Given a variable declaration, check if it has an integer initializer
167 * and if so, add a parameter corresponding to the variable to "value"
168 * with its value fixed to the integer initializer and return the result.
170 static __isl_give isl_set *extract_initialization(__isl_take isl_set *value,
171 ValueDecl *decl)
173 VarDecl *vd;
174 Expr *expr;
175 IntegerLiteral *il;
176 isl_int v;
177 isl_ctx *ctx;
178 isl_id *id;
179 isl_space *space;
180 isl_set *set;
182 vd = cast<VarDecl>(decl);
183 if (!vd)
184 return value;
185 if (!vd->getType()->isIntegerType())
186 return value;
187 expr = vd->getInit();
188 if (!expr)
189 return value;
190 il = cast<IntegerLiteral>(expr);
191 if (!il)
192 return value;
194 ctx = isl_set_get_ctx(value);
195 id = isl_id_alloc(ctx, vd->getName().str().c_str(), vd);
196 space = isl_space_params_alloc(ctx, 1);
197 space = isl_space_set_dim_id(space, isl_dim_param, 0, id);
198 set = isl_set_universe(space);
200 isl_int_init(v);
201 PetScan::extract_int(il, &v);
202 set = isl_set_fix(set, isl_dim_param, 0, v);
203 isl_int_clear(v);
205 return isl_set_intersect(value, set);
208 /* Handle pragmas of the form
210 * #pragma parameter identifier lower_bound upper_bound
212 * For each such pragma, intersect the context with the set
213 * [identifier] -> { [] : lower_bound <= identifier <= upper_bound }
215 struct PragmaParameterHandler : public PragmaHandler {
216 Sema &sema;
217 isl_set *&context;
218 isl_set *&context_value;
220 PragmaParameterHandler(Sema &sema, isl_set *&context,
221 isl_set *&context_value) :
222 PragmaHandler("parameter"), sema(sema), context(context),
223 context_value(context_value) {}
225 virtual void HandlePragma(Preprocessor &PP,
226 PragmaIntroducerKind Introducer,
227 Token &ScopTok) {
228 isl_id *id;
229 isl_ctx *ctx = isl_set_get_ctx(context);
230 isl_space *dim;
231 isl_set *set;
232 ValueDecl *vd;
233 Token token;
234 int lb;
235 int ub;
237 PP.Lex(token);
238 vd = get_value_decl(sema, token);
239 if (!vd) {
240 unsupported(PP, token.getLocation());
241 return;
244 PP.Lex(token);
245 if (!token.isLiteral()) {
246 unsupported(PP, token.getLocation());
247 return;
250 lb = get_int(token.getLiteralData());
252 PP.Lex(token);
253 if (!token.isLiteral()) {
254 unsupported(PP, token.getLocation());
255 return;
258 ub = get_int(token.getLiteralData());
260 id = isl_id_alloc(ctx, vd->getName().str().c_str(), vd);
261 dim = isl_space_params_alloc(ctx, 1);
262 dim = isl_space_set_dim_id(dim, isl_dim_param, 0, id);
264 set = isl_set_universe(dim);
266 set = isl_set_lower_bound_si(set, isl_dim_param, 0, lb);
267 set = isl_set_upper_bound_si(set, isl_dim_param, 0, ub);
269 context = isl_set_intersect(context, set);
271 context_value = extract_initialization(context_value, vd);
275 /* Handle pragmas of the form
277 * #pragma scop
279 * In particular, store the current location in loc.start.
281 struct PragmaScopHandler : public PragmaHandler {
282 ScopLoc &loc;
284 PragmaScopHandler(ScopLoc &loc) : PragmaHandler("scop"), loc(loc) {}
286 virtual void HandlePragma(Preprocessor &PP,
287 PragmaIntroducerKind Introducer,
288 Token &ScopTok) {
289 SourceManager &SM = PP.getSourceManager();
290 loc.start = SM.getFileOffset(ScopTok.getLocation());
294 /* Handle pragmas of the form
296 * #pragma endscop
298 * In particular, store the current location in loc.end.
300 struct PragmaEndScopHandler : public PragmaHandler {
301 ScopLoc &loc;
303 PragmaEndScopHandler(ScopLoc &loc) :
304 PragmaHandler("endscop"), loc(loc) {}
306 virtual void HandlePragma(Preprocessor &PP,
307 PragmaIntroducerKind Introducer,
308 Token &EndScopTok) {
309 SourceManager &SM = PP.getSourceManager();
310 loc.end = SM.getFileOffset(EndScopTok.getLocation());
314 /* Handle pragmas of the form
316 * #pragma live-out identifier, identifier, ...
318 * Each identifier on the line is stored in live_out.
320 struct PragmaLiveOutHandler : public PragmaHandler {
321 Sema &sema;
322 set<ValueDecl *> &live_out;
324 PragmaLiveOutHandler(Sema &sema, set<ValueDecl *> &live_out) :
325 PragmaHandler("live"), sema(sema), live_out(live_out) {}
327 virtual void HandlePragma(Preprocessor &PP,
328 PragmaIntroducerKind Introducer,
329 Token &ScopTok) {
330 Token token;
332 PP.Lex(token);
333 if (token.isNot(tok::minus))
334 return;
335 PP.Lex(token);
336 if (token.isNot(tok::identifier) ||
337 !token.getIdentifierInfo()->isStr("out"))
338 return;
340 PP.Lex(token);
341 while (token.isNot(tok::eod)) {
342 ValueDecl *vd;
344 vd = get_value_decl(sema, token);
345 if (!vd) {
346 unsupported(PP, token.getLocation());
347 return;
349 live_out.insert(vd);
350 PP.Lex(token);
351 if (token.is(tok::comma))
352 PP.Lex(token);
357 /* Extract a pet_scop from the appropriate function.
358 * If "function" is not NULL, then we only extract a pet_scop if the
359 * name of the function matches.
360 * If "autodetect" is false, then we only extract if we have seen
361 * scop and endscop pragmas and if these are situated inside the function
362 * body.
364 struct PetASTConsumer : public ASTConsumer {
365 Preprocessor &PP;
366 ASTContext &ast_context;
367 ScopLoc &loc;
368 const char *function;
369 bool autodetect;
370 isl_ctx *ctx;
371 struct pet_scop *scop;
373 PetASTConsumer(isl_ctx *ctx, Preprocessor &PP, ASTContext &ast_context,
374 ScopLoc &loc, const char *function, bool autodetect) :
375 ctx(ctx), PP(PP), ast_context(ast_context), loc(loc),
376 scop(NULL), function(function), autodetect(autodetect) { }
378 virtual void HandleTopLevelDecl(DeclGroupRef dg) {
379 DeclGroupRef::iterator it;
381 if (scop)
382 return;
383 for (it = dg.begin(); it != dg.end(); ++it) {
384 FunctionDecl *fd = dyn_cast<clang::FunctionDecl>(*it);
385 if (!fd)
386 continue;
387 if (!fd->hasBody())
388 continue;
389 if (function &&
390 fd->getNameInfo().getAsString() != function)
391 continue;
392 if (autodetect) {
393 PetScan ps(ctx, PP, ast_context, loc, 1);
394 scop = ps.scan(fd);
395 if (scop)
396 break;
397 else
398 continue;
400 if (!loc.end)
401 continue;
402 SourceManager &SM = PP.getSourceManager();
403 if (SM.getFileOffset(fd->getLocStart()) > loc.end)
404 continue;
405 if (SM.getFileOffset(fd->getLocEnd()) < loc.start)
406 continue;
407 PetScan ps(ctx, PP, ast_context, loc, 0);
408 scop = ps.scan(fd);
409 break;
414 static const char *ResourceDir = CLANG_PREFIX"/lib/clang/"CLANG_VERSION_STRING;
416 static const char *implicit_functions[] = {
417 "min", "max", "ceild", "floord"
420 static bool is_implicit(const IdentifierInfo *ident)
422 const char *name = ident->getNameStart();
423 for (int i = 0; i < ARRAY_SIZE(implicit_functions); ++i)
424 if (!strcmp(name, implicit_functions[i]))
425 return true;
426 return false;
429 /* Ignore implicit function declaration warnings on
430 * "min", "max", "ceild" and "floord" as we detect and handle these
431 * in PetScan.
433 struct MyDiagnosticPrinter : public TextDiagnosticPrinter {
434 const DiagnosticOptions *DiagOpts;
435 MyDiagnosticPrinter(const DiagnosticOptions &DO) :
436 DiagOpts(&DO), TextDiagnosticPrinter(llvm::errs(), DO) {}
437 virtual DiagnosticConsumer *clone(DiagnosticsEngine &Diags) const {
438 return new MyDiagnosticPrinter(*DiagOpts);
440 virtual void HandleDiagnostic(DiagnosticsEngine::Level level,
441 const DiagnosticInfo &info) {
442 if (info.getID() == diag::ext_implicit_function_decl &&
443 info.getNumArgs() == 1 &&
444 info.getArgKind(0) == DiagnosticsEngine::ak_identifierinfo &&
445 is_implicit(info.getArgIdentifier(0)))
446 /* ignore warning */;
447 else
448 TextDiagnosticPrinter::HandleDiagnostic(level, info);
452 static void update_arrays(struct pet_scop *scop,
453 map<ValueDecl *, isl_set *> &value_bounds,
454 set<ValueDecl *> &live_out)
456 map<ValueDecl *, isl_set *>::iterator vb_it;
457 set<ValueDecl *>::iterator lo_it;
459 if (!scop)
460 return;
462 for (int i = 0; i < scop->n_array; ++i) {
463 isl_id *id;
464 ValueDecl *decl;
465 pet_array *array = scop->arrays[i];
467 id = isl_set_get_tuple_id(array->extent);
468 decl = (ValueDecl *)isl_id_get_user(id);
469 isl_id_free(id);
471 vb_it = value_bounds.find(decl);
472 if (vb_it != value_bounds.end())
473 array->value_bounds = isl_set_copy(vb_it->second);
475 lo_it = live_out.find(decl);
476 if (lo_it != live_out.end())
477 array->live_out = 1;
481 /* Extract a pet_scop from the C source file called "filename".
482 * If "function" is not NULL, extract the pet_scop from the function
483 * with that name.
484 * If "autodetect" is set, extract any pet_scop we can find.
485 * Otherwise, extract the pet_scop from the region delimited
486 * by "scop" and "endscop" pragmas.
488 * We first set up the clang parser and then try to extract the
489 * pet_scop from the appropriate function in PetASTConsumer.
490 * If we have found a pet_scop, we add the context and value_bounds
491 * constraints specified through pragmas.
493 struct pet_scop *pet_scop_extract_from_C_source(isl_ctx *ctx,
494 const char *filename, const char *function, int autodetect)
496 isl_space *dim;
497 isl_set *context;
498 isl_set *context_value;
499 set<ValueDecl *> live_out;
500 map<ValueDecl *, isl_set *> value_bounds;
501 map<ValueDecl *, isl_set *>::iterator vb_it;
503 CompilerInstance *Clang = new CompilerInstance();
504 DiagnosticOptions DO;
505 Clang->createDiagnostics(0, NULL, new MyDiagnosticPrinter(DO));
506 DiagnosticsEngine &Diags = Clang->getDiagnostics();
507 Diags.setSuppressSystemWarnings(true);
508 Clang->createFileManager();
509 Clang->createSourceManager(Clang->getFileManager());
510 TargetOptions TO;
511 TO.Triple = llvm::sys::getHostTriple();
512 TargetInfo *target = TargetInfo::CreateTargetInfo(Diags, TO);
513 Clang->setTarget(target);
514 CompilerInvocation::setLangDefaults(Clang->getLangOpts(), IK_C,
515 LangStandard::lang_unspecified);
516 Clang->getHeaderSearchOpts().ResourceDir = ResourceDir;
517 Clang->createPreprocessor();
518 Preprocessor &PP = Clang->getPreprocessor();
520 ScopLoc loc;
522 const FileEntry *file = Clang->getFileManager().getFile(filename);
523 if (!file)
524 isl_die(ctx, isl_error_unknown, "unable to open file",
525 return NULL);
526 Clang->getSourceManager().createMainFileID(file);
528 Clang->createASTContext();
529 PetASTConsumer consumer(ctx, PP, Clang->getASTContext(),
530 loc, function, autodetect);
531 Sema *sema = new Sema(PP, Clang->getASTContext(), consumer);
533 if (!autodetect) {
534 PP.AddPragmaHandler(new PragmaScopHandler(loc));
535 PP.AddPragmaHandler(new PragmaEndScopHandler(loc));
536 PP.AddPragmaHandler(new PragmaLiveOutHandler(*sema, live_out));
539 dim = isl_space_params_alloc(ctx, 0);
540 context = isl_set_universe(isl_space_copy(dim));
541 context_value = isl_set_universe(dim);
542 PP.AddPragmaHandler(new PragmaParameterHandler(*sema, context,
543 context_value));
544 PP.AddPragmaHandler(new PragmaValueBoundsHandler(ctx, *sema, value_bounds));
546 Diags.getClient()->BeginSourceFile(Clang->getLangOpts(), &PP);
547 ParseAST(*sema);
548 Diags.getClient()->EndSourceFile();
550 delete sema;
551 delete Clang;
552 llvm::llvm_shutdown();
554 if (consumer.scop) {
555 consumer.scop->context = isl_set_intersect(context,
556 consumer.scop->context);
557 consumer.scop->context_value = isl_set_intersect(context_value,
558 consumer.scop->context_value);
559 } else {
560 isl_set_free(context);
561 isl_set_free(context_value);
564 update_arrays(consumer.scop, value_bounds, live_out);
566 for (vb_it = value_bounds.begin(); vb_it != value_bounds.end(); vb_it++)
567 isl_set_free(vb_it->second);
569 return consumer.scop;