2 * Copyright 2011 Leiden University. All rights reserved.
3 * Copyright 2012 Ecole Normale Superieure. All rights reserved.
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
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
38 #include <llvm/Support/raw_ostream.h>
39 #include <llvm/Support/ManagedStatic.h>
40 #include <llvm/Support/Host.h>
41 #include <clang/Basic/Version.h>
42 #include <clang/Basic/FileSystemOptions.h>
43 #include <clang/Basic/FileManager.h>
44 #include <clang/Basic/TargetOptions.h>
45 #include <clang/Basic/TargetInfo.h>
46 #include <clang/Driver/Compilation.h>
47 #include <clang/Driver/Driver.h>
48 #include <clang/Driver/Tool.h>
49 #include <clang/Frontend/CompilerInstance.h>
50 #include <clang/Frontend/CompilerInvocation.h>
51 #include <clang/Frontend/DiagnosticOptions.h>
52 #include <clang/Frontend/TextDiagnosticPrinter.h>
53 #include <clang/Frontend/HeaderSearchOptions.h>
54 #include <clang/Frontend/LangStandard.h>
55 #include <clang/Frontend/PreprocessorOptions.h>
56 #include <clang/Frontend/FrontendOptions.h>
57 #include <clang/Frontend/Utils.h>
58 #include <clang/Lex/HeaderSearch.h>
59 #include <clang/Lex/Preprocessor.h>
60 #include <clang/Lex/Pragma.h>
61 #include <clang/AST/ASTContext.h>
62 #include <clang/AST/ASTConsumer.h>
63 #include <clang/Sema/Sema.h>
64 #include <clang/Sema/SemaDiagnostic.h>
65 #include <clang/Parse/Parser.h>
66 #include <clang/Parse/ParseAST.h>
69 #include <isl/constraint.h>
76 #define ARRAY_SIZE(array) (sizeof(array)/sizeof(*array))
79 using namespace clang
;
80 using namespace clang::driver
;
82 /* Called if we found something we didn't expect in one of the pragmas.
83 * We'll provide more informative warnings later.
85 static void unsupported(Preprocessor
&PP
, SourceLocation loc
)
87 DiagnosticsEngine
&diag
= PP
.getDiagnostics();
88 unsigned id
= diag
.getCustomDiagID(DiagnosticsEngine::Warning
,
90 DiagnosticBuilder B
= diag
.Report(loc
, id
);
93 static int get_int(const char *s
)
95 return s
[0] == '"' ? atoi(s
+ 1) : atoi(s
);
98 static ValueDecl
*get_value_decl(Sema
&sema
, Token
&token
)
100 IdentifierInfo
*name
;
103 if (token
.isNot(tok::identifier
))
106 name
= token
.getIdentifierInfo();
107 decl
= sema
.LookupSingleName(sema
.TUScope
, name
,
108 token
.getLocation(), Sema::LookupOrdinaryName
);
109 return decl
? cast_or_null
<ValueDecl
>(decl
) : NULL
;
112 /* Handle pragmas of the form
114 * #pragma value_bounds identifier lower_bound upper_bound
116 * For each such pragma, add a mapping
117 * { identifier[] -> [i] : lower_bound <= i <= upper_bound }
120 struct PragmaValueBoundsHandler
: public PragmaHandler
{
123 isl_union_map
*value_bounds
;
125 PragmaValueBoundsHandler(isl_ctx
*ctx
, Sema
&sema
) :
126 PragmaHandler("value_bounds"), ctx(ctx
), sema(sema
) {
127 isl_space
*space
= isl_space_params_alloc(ctx
, 0);
128 value_bounds
= isl_union_map_empty(space
);
131 ~PragmaValueBoundsHandler() {
132 isl_union_map_free(value_bounds
);
135 virtual void HandlePragma(Preprocessor
&PP
,
136 PragmaIntroducerKind Introducer
,
147 vd
= get_value_decl(sema
, token
);
149 unsupported(PP
, token
.getLocation());
154 if (!token
.isLiteral()) {
155 unsupported(PP
, token
.getLocation());
159 lb
= get_int(token
.getLiteralData());
162 if (!token
.isLiteral()) {
163 unsupported(PP
, token
.getLocation());
167 ub
= get_int(token
.getLiteralData());
169 dim
= isl_space_alloc(ctx
, 0, 0, 1);
170 map
= isl_map_universe(dim
);
171 map
= isl_map_lower_bound_si(map
, isl_dim_out
, 0, lb
);
172 map
= isl_map_upper_bound_si(map
, isl_dim_out
, 0, ub
);
173 id
= isl_id_alloc(ctx
, vd
->getName().str().c_str(), vd
);
174 map
= isl_map_set_tuple_id(map
, isl_dim_in
, id
);
176 value_bounds
= isl_union_map_add_map(value_bounds
, map
);
180 /* Given a variable declaration, check if it has an integer initializer
181 * and if so, add a parameter corresponding to the variable to "value"
182 * with its value fixed to the integer initializer and return the result.
184 static __isl_give isl_set
*extract_initialization(__isl_take isl_set
*value
,
196 vd
= cast
<VarDecl
>(decl
);
199 if (!vd
->getType()->isIntegerType())
201 expr
= vd
->getInit();
204 il
= cast
<IntegerLiteral
>(expr
);
208 ctx
= isl_set_get_ctx(value
);
209 id
= isl_id_alloc(ctx
, vd
->getName().str().c_str(), vd
);
210 space
= isl_space_params_alloc(ctx
, 1);
211 space
= isl_space_set_dim_id(space
, isl_dim_param
, 0, id
);
212 set
= isl_set_universe(space
);
215 PetScan::extract_int(il
, &v
);
216 set
= isl_set_fix(set
, isl_dim_param
, 0, v
);
219 return isl_set_intersect(value
, set
);
222 /* Handle pragmas of the form
224 * #pragma parameter identifier lower_bound
226 * #pragma parameter identifier lower_bound upper_bound
228 * For each such pragma, intersect the context with the set
229 * [identifier] -> { [] : lower_bound <= identifier <= upper_bound }
231 struct PragmaParameterHandler
: public PragmaHandler
{
234 isl_set
*&context_value
;
236 PragmaParameterHandler(Sema
&sema
, isl_set
*&context
,
237 isl_set
*&context_value
) :
238 PragmaHandler("parameter"), sema(sema
), context(context
),
239 context_value(context_value
) {}
241 virtual void HandlePragma(Preprocessor
&PP
,
242 PragmaIntroducerKind Introducer
,
245 isl_ctx
*ctx
= isl_set_get_ctx(context
);
255 vd
= get_value_decl(sema
, token
);
257 unsupported(PP
, token
.getLocation());
262 if (!token
.isLiteral()) {
263 unsupported(PP
, token
.getLocation());
267 lb
= get_int(token
.getLiteralData());
270 if (token
.isLiteral()) {
272 ub
= get_int(token
.getLiteralData());
273 } else if (token
.isNot(tok::eod
)) {
274 unsupported(PP
, token
.getLocation());
278 id
= isl_id_alloc(ctx
, vd
->getName().str().c_str(), vd
);
279 dim
= isl_space_params_alloc(ctx
, 1);
280 dim
= isl_space_set_dim_id(dim
, isl_dim_param
, 0, id
);
282 set
= isl_set_universe(dim
);
284 set
= isl_set_lower_bound_si(set
, isl_dim_param
, 0, lb
);
286 set
= isl_set_upper_bound_si(set
, isl_dim_param
, 0, ub
);
288 context
= isl_set_intersect(context
, set
);
290 context_value
= extract_initialization(context_value
, vd
);
294 /* Handle pragmas of the form
298 * In particular, store the current location in loc.start.
300 struct PragmaScopHandler
: public PragmaHandler
{
303 PragmaScopHandler(ScopLoc
&loc
) : PragmaHandler("scop"), loc(loc
) {}
305 virtual void HandlePragma(Preprocessor
&PP
,
306 PragmaIntroducerKind Introducer
,
308 SourceManager
&SM
= PP
.getSourceManager();
309 loc
.start
= SM
.getFileOffset(ScopTok
.getLocation());
313 /* Handle pragmas of the form
317 * In particular, store the current location in loc.end.
319 struct PragmaEndScopHandler
: public PragmaHandler
{
322 PragmaEndScopHandler(ScopLoc
&loc
) :
323 PragmaHandler("endscop"), loc(loc
) {}
325 virtual void HandlePragma(Preprocessor
&PP
,
326 PragmaIntroducerKind Introducer
,
328 SourceManager
&SM
= PP
.getSourceManager();
329 loc
.end
= SM
.getFileOffset(EndScopTok
.getLocation());
333 /* Handle pragmas of the form
335 * #pragma live-out identifier, identifier, ...
337 * Each identifier on the line is stored in live_out.
339 struct PragmaLiveOutHandler
: public PragmaHandler
{
341 set
<ValueDecl
*> &live_out
;
343 PragmaLiveOutHandler(Sema
&sema
, set
<ValueDecl
*> &live_out
) :
344 PragmaHandler("live"), sema(sema
), live_out(live_out
) {}
346 virtual void HandlePragma(Preprocessor
&PP
,
347 PragmaIntroducerKind Introducer
,
352 if (token
.isNot(tok::minus
))
355 if (token
.isNot(tok::identifier
) ||
356 !token
.getIdentifierInfo()->isStr("out"))
360 while (token
.isNot(tok::eod
)) {
363 vd
= get_value_decl(sema
, token
);
365 unsupported(PP
, token
.getLocation());
370 if (token
.is(tok::comma
))
376 /* Extract a pet_scop from the appropriate function.
377 * If "function" is not NULL, then we only extract a pet_scop if the
378 * name of the function matches.
379 * If "autodetect" is false, then we only extract if we have seen
380 * scop and endscop pragmas and if these are situated inside the function
383 struct PetASTConsumer
: public ASTConsumer
{
385 ASTContext
&ast_context
;
387 const char *function
;
390 struct pet_scop
*scop
;
391 PragmaValueBoundsHandler
*vb_handler
;
393 PetASTConsumer(isl_ctx
*ctx
, Preprocessor
&PP
, ASTContext
&ast_context
,
394 ScopLoc
&loc
, const char *function
, bool autodetect
) :
395 ctx(ctx
), PP(PP
), ast_context(ast_context
), loc(loc
),
396 scop(NULL
), function(function
), autodetect(autodetect
),
399 void handle_value_bounds(Sema
*sema
) {
400 vb_handler
= new PragmaValueBoundsHandler(ctx
, *sema
);
401 PP
.AddPragmaHandler(vb_handler
);
404 __isl_give isl_union_map
*get_value_bounds() {
405 return isl_union_map_copy(vb_handler
->value_bounds
);
408 virtual HandleTopLevelDeclReturn
HandleTopLevelDecl(DeclGroupRef dg
) {
409 DeclGroupRef::iterator it
;
412 return HandleTopLevelDeclContinue
;
413 for (it
= dg
.begin(); it
!= dg
.end(); ++it
) {
414 isl_union_map
*vb
= vb_handler
->value_bounds
;
415 FunctionDecl
*fd
= dyn_cast
<clang::FunctionDecl
>(*it
);
421 fd
->getNameInfo().getAsString() != function
)
424 PetScan
ps(PP
, ast_context
, loc
, 1,
425 isl_union_map_copy(vb
));
434 SourceManager
&SM
= PP
.getSourceManager();
435 if (SM
.getFileOffset(fd
->getLocStart()) > loc
.end
)
437 if (SM
.getFileOffset(fd
->getLocEnd()) < loc
.start
)
439 PetScan
ps(PP
, ast_context
, loc
, 0,
440 isl_union_map_copy(vb
));
445 return HandleTopLevelDeclContinue
;
449 static const char *ResourceDir
= CLANG_PREFIX
"/lib/clang/"CLANG_VERSION_STRING
;
451 static const char *implicit_functions
[] = {
452 "min", "max", "ceild", "floord"
455 static bool is_implicit(const IdentifierInfo
*ident
)
457 const char *name
= ident
->getNameStart();
458 for (int i
= 0; i
< ARRAY_SIZE(implicit_functions
); ++i
)
459 if (!strcmp(name
, implicit_functions
[i
]))
464 /* Ignore implicit function declaration warnings on
465 * "min", "max", "ceild" and "floord" as we detect and handle these
468 * The cloned field keeps track of whether the clone method
469 * has ever been called. Newer clangs (by default) clone
470 * the DiagnosticConsumer passed to createDiagnostics and
471 * then take ownership of the clone, which means that
472 * the original has to be deleted by the calling code.
474 struct MyDiagnosticPrinter
: public TextDiagnosticPrinter
{
475 const DiagnosticOptions
*DiagOpts
;
477 MyDiagnosticPrinter(const DiagnosticOptions
&DO
) :
478 DiagOpts(&DO
), TextDiagnosticPrinter(llvm::errs(), DO
) {}
479 virtual DiagnosticConsumer
*clone(DiagnosticsEngine
&Diags
) const {
481 return new MyDiagnosticPrinter(*DiagOpts
);
483 virtual void HandleDiagnostic(DiagnosticsEngine::Level level
,
484 const DiagnosticInfo
&info
) {
485 if (info
.getID() == diag::ext_implicit_function_decl
&&
486 info
.getNumArgs() == 1 &&
487 info
.getArgKind(0) == DiagnosticsEngine::ak_identifierinfo
&&
488 is_implicit(info
.getArgIdentifier(0)))
489 /* ignore warning */;
491 TextDiagnosticPrinter::HandleDiagnostic(level
, info
);
495 bool MyDiagnosticPrinter::cloned
= false;
497 /* For each array in "scop", set its value_bounds property
498 * based on the infofrmation in "value_bounds" and
499 * mark it as live_out if it appears in "live_out".
501 static void update_arrays(struct pet_scop
*scop
,
502 __isl_take isl_union_map
*value_bounds
, set
<ValueDecl
*> &live_out
)
504 set
<ValueDecl
*>::iterator lo_it
;
505 isl_ctx
*ctx
= isl_union_map_get_ctx(value_bounds
);
508 isl_union_map_free(value_bounds
);
512 for (int i
= 0; i
< scop
->n_array
; ++i
) {
517 pet_array
*array
= scop
->arrays
[i
];
519 id
= isl_set_get_tuple_id(array
->extent
);
520 decl
= (ValueDecl
*)isl_id_get_user(id
);
522 space
= isl_space_alloc(ctx
, 0, 0, 1);
523 space
= isl_space_set_tuple_id(space
, isl_dim_in
, id
);
525 bounds
= isl_union_map_extract_map(value_bounds
, space
);
526 if (!isl_map_plain_is_empty(bounds
))
527 array
->value_bounds
= isl_map_range(bounds
);
529 isl_map_free(bounds
);
531 lo_it
= live_out
.find(decl
);
532 if (lo_it
!= live_out
.end())
536 isl_union_map_free(value_bounds
);
541 #ifdef HAVE_CXXISPRODUCTION
542 static Driver
*construct_driver(const char *binary
, DiagnosticsEngine
&Diags
)
544 return new Driver(binary
, llvm::sys::getDefaultTargetTriple(),
545 "", false, false, Diags
);
548 static Driver
*construct_driver(const char *binary
, DiagnosticsEngine
&Diags
)
550 return new Driver(binary
, llvm::sys::getDefaultTargetTriple(),
555 /* Create a CompilerInvocation object that stores the command line
556 * arguments constructed by the driver.
557 * The arguments are mainly useful for setting up the system include
558 * paths on newer clangs and on some platforms.
560 static CompilerInvocation
*construct_invocation(const char *filename
,
561 DiagnosticsEngine
&Diags
)
563 const char *binary
= CLANG_PREFIX
"/bin/clang";
564 const llvm::OwningPtr
<Driver
> driver(construct_driver(binary
, Diags
));
565 std::vector
<const char *> Argv
;
566 Argv
.push_back(binary
);
567 Argv
.push_back(filename
);
568 const llvm::OwningPtr
<Compilation
> compilation(
569 driver
->BuildCompilation(llvm::ArrayRef
<const char *>(Argv
)));
570 JobList
&Jobs
= compilation
->getJobs();
574 Command
*cmd
= cast
<Command
>(*Jobs
.begin());
575 if (strcmp(cmd
->getCreator().getName(), "clang"))
578 const ArgStringList
*args
= &cmd
->getArguments();
580 CompilerInvocation
*invocation
= new CompilerInvocation
;
581 CompilerInvocation::CreateFromArgs(*invocation
, args
->data() + 1,
582 args
->data() + args
->size(),
589 static CompilerInvocation
*construct_invocation(const char *filename
,
590 DiagnosticsEngine
&Diags
)
597 /* Extract a pet_scop from the C source file called "filename".
598 * If "function" is not NULL, extract the pet_scop from the function
600 * If "autodetect" is set, extract any pet_scop we can find.
601 * Otherwise, extract the pet_scop from the region delimited
602 * by "scop" and "endscop" pragmas.
604 * We first set up the clang parser and then try to extract the
605 * pet_scop from the appropriate function in PetASTConsumer.
606 * If we have found a pet_scop, we add the context and value_bounds
607 * constraints specified through pragmas.
609 static struct pet_scop
*scop_extract_from_C_source(isl_ctx
*ctx
,
610 const char *filename
, const char *function
, pet_options
*options
)
614 isl_set
*context_value
;
616 set
<ValueDecl
*> live_out
;
617 isl_union_map
*value_bounds
;
619 CompilerInstance
*Clang
= new CompilerInstance();
620 DiagnosticOptions DO
;
621 MyDiagnosticPrinter
*printer
= new MyDiagnosticPrinter(DO
);
622 Clang
->createDiagnostics(0, NULL
, printer
);
625 DiagnosticsEngine
&Diags
= Clang
->getDiagnostics();
626 Diags
.setSuppressSystemWarnings(true);
627 CompilerInvocation
*invocation
= construct_invocation(filename
, Diags
);
629 Clang
->setInvocation(invocation
);
630 Clang
->createFileManager();
631 Clang
->createSourceManager(Clang
->getFileManager());
633 TO
.Triple
= llvm::sys::getDefaultTargetTriple();
634 TargetInfo
*target
= TargetInfo::CreateTargetInfo(Diags
, TO
);
635 Clang
->setTarget(target
);
636 CompilerInvocation::setLangDefaults(Clang
->getLangOpts(), IK_C
,
637 LangStandard::lang_unspecified
);
638 HeaderSearchOptions
&HSO
= Clang
->getHeaderSearchOpts();
639 HSO
.ResourceDir
= ResourceDir
;
640 for (int i
= 0; i
< options
->n_path
; ++i
)
641 HSO
.AddPath(options
->paths
[i
],
642 frontend::Angled
, true, false, false);
643 PreprocessorOptions
&PO
= Clang
->getPreprocessorOpts();
644 for (int i
= 0; i
< options
->n_define
; ++i
)
645 PO
.addMacroDef(options
->defines
[i
]);
646 Clang
->createPreprocessor();
647 Preprocessor
&PP
= Clang
->getPreprocessor();
651 const FileEntry
*file
= Clang
->getFileManager().getFile(filename
);
653 isl_die(ctx
, isl_error_unknown
, "unable to open file",
654 do { delete Clang
; return NULL
; } while (0));
655 Clang
->getSourceManager().createMainFileID(file
);
657 Clang
->createASTContext();
658 PetASTConsumer
consumer(ctx
, PP
, Clang
->getASTContext(),
659 loc
, function
, options
->autodetect
);
660 Sema
*sema
= new Sema(PP
, Clang
->getASTContext(), consumer
);
662 if (!options
->autodetect
) {
663 PP
.AddPragmaHandler(new PragmaScopHandler(loc
));
664 PP
.AddPragmaHandler(new PragmaEndScopHandler(loc
));
665 PP
.AddPragmaHandler(new PragmaLiveOutHandler(*sema
, live_out
));
668 dim
= isl_space_params_alloc(ctx
, 0);
669 context
= isl_set_universe(isl_space_copy(dim
));
670 context_value
= isl_set_universe(dim
);
671 PP
.AddPragmaHandler(new PragmaParameterHandler(*sema
, context
,
673 consumer
.handle_value_bounds(sema
);
675 Diags
.getClient()->BeginSourceFile(Clang
->getLangOpts(), &PP
);
677 Diags
.getClient()->EndSourceFile();
679 scop
= consumer
.scop
;
680 if (Diags
.hasErrorOccurred()) {
686 scop
->context
= isl_set_intersect(context
, scop
->context
);
687 scop
->context_value
= isl_set_intersect(context_value
,
688 scop
->context_value
);
690 isl_set_free(context
);
691 isl_set_free(context_value
);
694 scop
= pet_scop_anonymize(scop
);
696 update_arrays(scop
, consumer
.get_value_bounds(), live_out
);
704 struct pet_scop
*pet_scop_extract_from_C_source(isl_ctx
*ctx
,
705 const char *filename
, const char *function
)
708 pet_options
*options
;
709 bool allocated
= false;
711 options
= isl_ctx_peek_pet_options(ctx
);
713 options
= pet_options_new_with_defaults();
717 scop
= scop_extract_from_C_source(ctx
, filename
, function
, options
);
718 llvm::llvm_shutdown();
721 pet_options_free(options
);