pet.cc: extract out get_value_decl
[pet.git] / pet.cc
blob877b68558b0e77b1ed8bb4003395e4ec31e84470
1 #include <stdlib.h>
2 #include <map>
3 #include <iostream>
4 #include <llvm/Support/raw_ostream.h>
5 #include <llvm/Support/ManagedStatic.h>
6 #include <llvm/Support/Host.h>
7 #include <clang/Basic/Version.h>
8 #include <clang/Basic/FileSystemOptions.h>
9 #include <clang/Basic/FileManager.h>
10 #include <clang/Basic/TargetOptions.h>
11 #include <clang/Basic/TargetInfo.h>
12 #include <clang/Frontend/CompilerInvocation.h>
13 #include <clang/Frontend/DiagnosticOptions.h>
14 #include <clang/Frontend/TextDiagnosticPrinter.h>
15 #include <clang/Frontend/HeaderSearchOptions.h>
16 #include <clang/Frontend/LangStandard.h>
17 #include <clang/Frontend/PreprocessorOptions.h>
18 #include <clang/Frontend/FrontendOptions.h>
19 #include <clang/Frontend/Utils.h>
20 #include <clang/Lex/HeaderSearch.h>
21 #include <clang/Lex/Preprocessor.h>
22 #include <clang/Lex/Pragma.h>
23 #include <clang/AST/ASTContext.h>
24 #include <clang/AST/ASTConsumer.h>
25 #include <clang/Sema/Sema.h>
26 #include <clang/Sema/SemaDiagnostic.h>
27 #include <clang/Parse/Parser.h>
28 #include <clang/Parse/ParseAST.h>
30 #include <isl/ctx.h>
31 #include <isl/constraint.h>
33 #include "scan.h"
35 #include "config.h"
37 #define ARRAY_SIZE(array) (sizeof(array)/sizeof(*array))
39 using namespace std;
40 using namespace clang;
42 /* Called if we found something we didn't expect in one of the pragmas.
43 * We'll provide more informative warnings later.
45 static void unsupported(Preprocessor &PP, SourceLocation loc)
47 Diagnostic &diag = PP.getDiagnostics();
48 unsigned id = diag.getCustomDiagID(Diagnostic::Warning, "unsupported");
49 DiagnosticBuilder B = diag.Report(loc, id);
52 /* Set the lower and upper bounds on the given dimension of "set"
53 * to "lb" and "ub".
55 static __isl_give isl_set *set_bounds(__isl_take isl_set *set,
56 enum isl_dim_type type, int pos, int lb, int ub)
58 isl_constraint *c;
60 c = isl_inequality_alloc(isl_set_get_dim(set));
61 isl_constraint_set_coefficient_si(c, type, pos, 1);
62 isl_constraint_set_constant_si(c, -lb);
63 set = isl_set_add_constraint(set, c);
65 c = isl_inequality_alloc(isl_set_get_dim(set));
66 isl_constraint_set_coefficient_si(c, type, pos, -1);
67 isl_constraint_set_constant_si(c, ub);
68 set = isl_set_add_constraint(set, c);
70 return set;
73 static int get_int(const char *s)
75 return s[0] == '"' ? atoi(s + 1) : atoi(s);
78 static ValueDecl *get_value_decl(Sema &sema, Token &token)
80 IdentifierInfo *name;
81 Decl *decl;
83 if (token.isNot(tok::identifier))
84 return NULL;
86 name = token.getIdentifierInfo();
87 decl = sema.LookupSingleName(sema.TUScope, name,
88 token.getLocation(), Sema::LookupOrdinaryName);
89 return decl ? cast_or_null<ValueDecl>(decl) : NULL;
92 /* Handle pragmas of the form
94 * #pragma value_bounds identifier lower_bound upper_bound
96 * For each such pragma, add a mapping from the ValueDecl corresponding
97 * to "identifier" to a set { [i] : lower_bound <= i <= upper_bound }
98 * to the map value_bounds.
100 struct PragmaValueBoundsHandler : public PragmaHandler {
101 Sema &sema;
102 isl_ctx *ctx;
103 map<ValueDecl *, isl_set *> &value_bounds;
105 PragmaValueBoundsHandler(isl_ctx *ctx, Sema &sema,
106 map<ValueDecl *, isl_set *> &value_bounds) :
107 PragmaHandler("value_bounds"), ctx(ctx), sema(sema),
108 value_bounds(value_bounds) {}
110 virtual void HandlePragma(Preprocessor &PP,
111 PragmaIntroducerKind Introducer,
112 Token &ScopTok) {
113 isl_dim *dim;
114 isl_set *set;
115 ValueDecl *vd;
116 Token token;
117 int lb;
118 int ub;
120 PP.Lex(token);
121 vd = get_value_decl(sema, token);
122 if (!vd) {
123 unsupported(PP, token.getLocation());
124 return;
127 PP.Lex(token);
128 if (!token.isLiteral()) {
129 unsupported(PP, token.getLocation());
130 return;
133 lb = get_int(token.getLiteralData());
135 PP.Lex(token);
136 if (!token.isLiteral()) {
137 unsupported(PP, token.getLocation());
138 return;
141 ub = get_int(token.getLiteralData());
143 dim = isl_dim_set_alloc(ctx, 0, 1);
144 set = isl_set_universe(dim);
145 set = set_bounds(set, isl_dim_set, 0, lb, ub);
147 value_bounds[vd] = set;
151 /* Handle pragmas of the form
153 * #pragma parameter identifier lower_bound upper_bound
155 * For each such pragma, intersect the context with the set
156 * [identifier] -> { [] : lower_bound <= identifier <= upper_bound }
158 struct PragmaParameterHandler : public PragmaHandler {
159 Sema &sema;
160 isl_set *&context;
162 PragmaParameterHandler(Sema &sema, isl_set *&context) :
163 PragmaHandler("parameter"), sema(sema), context(context) {}
165 virtual void HandlePragma(Preprocessor &PP,
166 PragmaIntroducerKind Introducer,
167 Token &ScopTok) {
168 isl_id *id;
169 isl_ctx *ctx = isl_set_get_ctx(context);
170 isl_dim *dim;
171 isl_set *set;
172 ValueDecl *vd;
173 Token token;
174 int lb;
175 int ub;
177 PP.Lex(token);
178 vd = get_value_decl(sema, token);
179 if (!vd) {
180 unsupported(PP, token.getLocation());
181 return;
184 PP.Lex(token);
185 if (!token.isLiteral()) {
186 unsupported(PP, token.getLocation());
187 return;
190 lb = get_int(token.getLiteralData());
192 PP.Lex(token);
193 if (!token.isLiteral()) {
194 unsupported(PP, token.getLocation());
195 return;
198 ub = get_int(token.getLiteralData());
200 id = isl_id_alloc(ctx, vd->getName().str().c_str(), vd);
201 dim = isl_dim_set_alloc(ctx, 1, 0);
202 dim = isl_dim_set_dim_id(dim, isl_dim_param, 0, id);
204 set = isl_set_universe(dim);
206 set = set_bounds(set, isl_dim_param, 0, lb, ub);
208 context = isl_set_intersect(context, set);
212 /* Handle pragmas of the form
214 * #pragma scop
216 * In particular, store the current location in loc.start.
218 struct PragmaScopHandler : public PragmaHandler {
219 ScopLoc &loc;
221 PragmaScopHandler(ScopLoc &loc) : PragmaHandler("scop"), loc(loc) {}
223 virtual void HandlePragma(Preprocessor &PP,
224 PragmaIntroducerKind Introducer,
225 Token &ScopTok) {
226 SourceManager &SM = PP.getSourceManager();
227 loc.start = SM.getFileOffset(ScopTok.getLocation());
231 /* Handle pragmas of the form
233 * #pragma endscop
235 * In particular, store the current location in loc.end.
237 struct PragmaEndScopHandler : public PragmaHandler {
238 ScopLoc &loc;
240 PragmaEndScopHandler(ScopLoc &loc) :
241 PragmaHandler("endscop"), loc(loc) {}
243 virtual void HandlePragma(Preprocessor &PP,
244 PragmaIntroducerKind Introducer,
245 Token &EndScopTok) {
246 SourceManager &SM = PP.getSourceManager();
247 loc.end = SM.getFileOffset(EndScopTok.getLocation());
251 /* Extract a pet_scop from the appropriate function.
252 * If "function" is not NULL, then we only extract a pet_scop if the
253 * name of the function matches.
254 * If "autodetect" is false, then we only extract if we have seen
255 * scop and endscop pragmas and if these are situated inside the function
256 * body.
258 struct PetASTConsumer : public ASTConsumer {
259 Preprocessor &PP;
260 ASTContext &ast_context;
261 ScopLoc &loc;
262 const char *function;
263 bool autodetect;
264 isl_ctx *ctx;
265 struct pet_scop *scop;
267 PetASTConsumer(isl_ctx *ctx, Preprocessor &PP, ASTContext &ast_context,
268 ScopLoc &loc, const char *function, bool autodetect) :
269 ctx(ctx), PP(PP), ast_context(ast_context), loc(loc),
270 scop(NULL), function(function), autodetect(autodetect) { }
272 virtual void HandleTopLevelDecl(DeclGroupRef dg) {
273 DeclGroupRef::iterator it;
275 if (scop)
276 return;
277 for (it = dg.begin(); it != dg.end(); ++it) {
278 FunctionDecl *fd = dyn_cast<clang::FunctionDecl>(*it);
279 if (!fd)
280 continue;
281 if (!fd->hasBody())
282 continue;
283 if (function &&
284 fd->getNameInfo().getAsString() != function)
285 continue;
286 if (autodetect) {
287 PetScan ps(ctx, PP, ast_context, loc, 1);
288 scop = ps.scan(fd);
289 if (scop)
290 break;
291 else
292 continue;
294 if (!loc.end)
295 continue;
296 SourceManager &SM = PP.getSourceManager();
297 if (SM.getFileOffset(fd->getLocStart()) > loc.end)
298 continue;
299 if (SM.getFileOffset(fd->getLocEnd()) < loc.start)
300 continue;
301 PetScan ps(ctx, PP, ast_context, loc, 0);
302 scop = ps.scan(fd);
303 break;
308 static const char *ResourceDir = CLANG_PREFIX"/lib/clang/"CLANG_VERSION_STRING;
310 static const char *implicit_functions[] = {
311 "min", "max", "ceild", "floord"
314 static bool is_implicit(const IdentifierInfo *ident)
316 const char *name = ident->getNameStart();
317 for (int i = 0; i < ARRAY_SIZE(implicit_functions); ++i)
318 if (!strcmp(name, implicit_functions[i]))
319 return true;
320 return false;
323 /* Ignore implicit function declaration warnings on
324 * "min", "max", "ceild" and "floord" as we detect and handle these
325 * in PetScan.
327 struct MyDiagnosticPrinter : public TextDiagnosticPrinter {
328 MyDiagnosticPrinter(const DiagnosticOptions &DO) :
329 TextDiagnosticPrinter(llvm::errs(), DO) {}
330 virtual void HandleDiagnostic(Diagnostic::Level level,
331 const DiagnosticInfo &info) {
332 if (info.getID() == diag::ext_implicit_function_decl &&
333 info.getNumArgs() == 1 &&
334 info.getArgKind(0) == Diagnostic::ak_identifierinfo &&
335 is_implicit(info.getArgIdentifier(0)))
336 /* ignore warning */;
337 else
338 TextDiagnosticPrinter::HandleDiagnostic(level, info);
342 /* Extract a pet_scop from the C source file called "filename".
343 * If "function" is not NULL, extract the pet_scop from the function
344 * with that name.
345 * If "autodetect" is set, extract any pet_scop we can find.
346 * Otherwise, extract the pet_scop from the region delimited
347 * by "scop" and "endscop" pragmas.
349 * We first set up the clang parser and then try to extract the
350 * pet_scop from the appropriate function in PetASTConsumer.
351 * If we have found a pet_scop, we add the context and value_bounds
352 * constraints specified through pragmas.
354 struct pet_scop *pet_scop_extract_from_C_source(isl_ctx *ctx,
355 const char *filename, const char *function, int autodetect)
357 isl_dim *dim;
358 isl_set *context;
359 map<ValueDecl *, isl_set *> value_bounds;
360 map<ValueDecl *, isl_set *>::iterator vb_it;
362 FileSystemOptions FO;
363 FileManager FM(FO);
364 const FileEntry *file = FM.getFile(filename);
365 if (!file)
366 isl_die(ctx, isl_error_unknown, "unable to open file",
367 return NULL);
369 llvm::IntrusiveRefCntPtr<DiagnosticIDs> DiagID(new DiagnosticIDs());
370 DiagnosticOptions DO;
371 Diagnostic Diags(DiagID, new MyDiagnosticPrinter(DO));
372 TargetOptions TO;
373 TO.Triple = llvm::sys::getHostTriple();
374 TargetInfo *target = TargetInfo::CreateTargetInfo(Diags, TO);
375 SourceManager SM(Diags, FM);
376 HeaderSearch HS(FM);
377 LangOptions LO;
378 CompilerInvocation::setLangDefaults(LO, IK_C,
379 LangStandard::lang_unspecified);
380 Preprocessor PP(Diags, LO, *target, SM, HS);
381 HeaderSearchOptions HSO;
382 PreprocessorOptions PPO;
383 FrontendOptions FEO;
384 HSO.ResourceDir = ResourceDir;
385 InitializePreprocessor(PP, PPO, HSO, FEO);
387 ScopLoc loc;
389 if (!autodetect) {
390 PP.AddPragmaHandler(new PragmaScopHandler(loc));
391 PP.AddPragmaHandler(new PragmaEndScopHandler(loc));
394 SM.createMainFileID(file);
396 ASTContext ast_context(LO, PP.getSourceManager(),
397 *target, PP.getIdentifierTable(), PP.getSelectorTable(),
398 PP.getBuiltinInfo(), 0);
399 PetASTConsumer consumer(ctx, PP, ast_context,
400 loc, function, autodetect);
401 Sema sema(PP, ast_context, consumer);
403 dim = isl_dim_set_alloc(ctx, 0, 0);
404 context = isl_set_universe(dim);
405 PP.AddPragmaHandler(new PragmaParameterHandler(sema, context));
406 PP.AddPragmaHandler(new PragmaValueBoundsHandler(ctx, sema, value_bounds));
408 Diags.getClient()->BeginSourceFile(LO, &PP);
409 ParseAST(sema);
410 Diags.getClient()->EndSourceFile();
412 delete target;
413 llvm::llvm_shutdown();
415 if (consumer.scop)
416 consumer.scop->context = isl_set_intersect(context,
417 consumer.scop->context);
418 else
419 isl_set_free(context);
421 if (consumer.scop) {
422 for (int i = 0; i < consumer.scop->n_array; ++i) {
423 isl_id *id;
424 ValueDecl *decl;
425 pet_array *array = consumer.scop->arrays[i];
427 id = isl_set_get_tuple_id(array->extent);
428 decl = (ValueDecl *)isl_id_get_user(id);
429 isl_id_free(id);
431 vb_it = value_bounds.find(decl);
432 if (vb_it != value_bounds.end())
433 array->value_bounds = isl_set_copy(vb_it->second);
437 for (vb_it = value_bounds.begin(); vb_it != value_bounds.end(); vb_it++)
438 isl_set_free(vb_it->second);
440 return consumer.scop;