2 * Copyright 2011 Leiden University. All rights reserved.
3 * Copyright 2012-2014 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
42 #ifdef HAVE_ADT_OWNINGPTR_H
43 #include <llvm/ADT/OwningPtr.h>
47 #ifdef HAVE_LLVM_OPTION_ARG_H
48 #include <llvm/Option/Arg.h>
50 #include <llvm/Support/raw_ostream.h>
51 #include <llvm/Support/ManagedStatic.h>
52 #include <llvm/Support/MemoryBuffer.h>
53 #ifdef HAVE_TARGETPARSER_HOST_H
54 #include <llvm/TargetParser/Host.h>
56 #include <llvm/Support/Host.h>
58 #include <clang/Basic/Version.h>
59 #include <clang/Basic/Builtins.h>
60 #include <clang/Basic/FileSystemOptions.h>
61 #include <clang/Basic/FileManager.h>
62 #include <clang/Basic/TargetOptions.h>
63 #include <clang/Basic/TargetInfo.h>
64 #include <clang/Driver/Compilation.h>
65 #include <clang/Driver/Driver.h>
66 #include <clang/Driver/Tool.h>
67 #include <clang/Frontend/CompilerInstance.h>
68 #include <clang/Frontend/CompilerInvocation.h>
69 #ifdef HAVE_BASIC_DIAGNOSTICOPTIONS_H
70 #include <clang/Basic/DiagnosticOptions.h>
72 #include <clang/Frontend/DiagnosticOptions.h>
74 #include <clang/Frontend/TextDiagnosticPrinter.h>
75 #ifdef HAVE_LEX_HEADERSEARCHOPTIONS_H
76 #include <clang/Lex/HeaderSearchOptions.h>
78 #include <clang/Frontend/HeaderSearchOptions.h>
80 #ifdef HAVE_CLANG_BASIC_LANGSTANDARD_H
81 #include <clang/Basic/LangStandard.h>
83 #include <clang/Frontend/LangStandard.h>
85 #ifdef HAVE_LEX_PREPROCESSOROPTIONS_H
86 #include <clang/Lex/PreprocessorOptions.h>
88 #include <clang/Frontend/PreprocessorOptions.h>
90 #include <clang/Frontend/FrontendOptions.h>
91 #include <clang/Frontend/Utils.h>
92 #include <clang/Lex/HeaderSearch.h>
93 #include <clang/Lex/Preprocessor.h>
94 #include <clang/Lex/Pragma.h>
95 #include <clang/AST/ASTContext.h>
96 #include <clang/AST/ASTConsumer.h>
97 #include <clang/Sema/Sema.h>
98 #include <clang/Sema/SemaDiagnostic.h>
99 #include <clang/Parse/Parser.h>
100 #include <clang/Parse/ParseAST.h>
103 #include <isl/constraint.h>
107 #include "clang_compatibility.h"
113 #define ARRAY_SIZE(array) (sizeof(array)/sizeof(*array))
116 using namespace clang
;
117 using namespace clang::driver
;
118 #ifdef HAVE_LLVM_OPTION_ARG_H
119 using namespace llvm::opt
;
122 #ifdef HAVE_ADT_OWNINGPTR_H
123 #define unique_ptr llvm::OwningPtr
126 /* Called if we found something we didn't expect in one of the pragmas.
127 * We'll provide more informative warnings later.
129 static void unsupported(Preprocessor
&PP
, SourceLocation loc
)
131 DiagnosticsEngine
&diag
= PP
.getDiagnostics();
132 unsigned id
= diag
.getCustomDiagID(DiagnosticsEngine::Warning
,
134 DiagnosticBuilder B
= diag
.Report(loc
, id
);
137 static int get_int(const char *s
)
139 return s
[0] == '"' ? atoi(s
+ 1) : atoi(s
);
142 static ValueDecl
*get_value_decl(Sema
&sema
, Token
&token
)
144 IdentifierInfo
*name
;
147 if (token
.isNot(tok::identifier
))
150 name
= token
.getIdentifierInfo();
151 decl
= sema
.LookupSingleName(sema
.TUScope
, name
,
152 token
.getLocation(), Sema::LookupOrdinaryName
);
153 return decl
? cast_or_null
<ValueDecl
>(decl
) : NULL
;
156 /* Handle pragmas of the form
158 * #pragma value_bounds identifier lower_bound upper_bound
160 * For each such pragma, add a mapping
161 * { identifier[] -> [i] : lower_bound <= i <= upper_bound }
164 struct PragmaValueBoundsHandler
: public PragmaHandler
{
167 isl_union_map
*value_bounds
;
169 PragmaValueBoundsHandler(isl_ctx
*ctx
, Sema
&sema
) :
170 PragmaHandler("value_bounds"), sema(sema
), ctx(ctx
) {
171 isl_space
*space
= isl_space_params_alloc(ctx
, 0);
172 value_bounds
= isl_union_map_empty(space
);
175 ~PragmaValueBoundsHandler() {
176 isl_union_map_free(value_bounds
);
179 virtual void HandlePragma(Preprocessor
&PP
,
180 PragmaIntroducer Introducer
,
191 vd
= get_value_decl(sema
, token
);
193 unsupported(PP
, token
.getLocation());
198 if (!token
.isLiteral()) {
199 unsupported(PP
, token
.getLocation());
203 lb
= get_int(token
.getLiteralData());
206 if (!token
.isLiteral()) {
207 unsupported(PP
, token
.getLocation());
211 ub
= get_int(token
.getLiteralData());
213 dim
= isl_space_alloc(ctx
, 0, 0, 1);
214 map
= isl_map_universe(dim
);
215 map
= isl_map_lower_bound_si(map
, isl_dim_out
, 0, lb
);
216 map
= isl_map_upper_bound_si(map
, isl_dim_out
, 0, ub
);
217 id
= isl_id_alloc(ctx
, vd
->getName().str().c_str(), vd
);
218 map
= isl_map_set_tuple_id(map
, isl_dim_in
, id
);
220 value_bounds
= isl_union_map_add_map(value_bounds
, map
);
224 /* Given a variable declaration, check if it has an integer initializer
225 * and if so, add a parameter corresponding to the variable to "value"
226 * with its value fixed to the integer initializer and return the result.
228 static __isl_give isl_set
*extract_initialization(__isl_take isl_set
*value
,
240 vd
= cast
<VarDecl
>(decl
);
243 if (!vd
->getType()->isIntegerType())
245 expr
= vd
->getInit();
248 il
= cast
<IntegerLiteral
>(expr
);
252 ctx
= isl_set_get_ctx(value
);
253 id
= isl_id_alloc(ctx
, vd
->getName().str().c_str(), vd
);
254 space
= isl_space_params_alloc(ctx
, 1);
255 space
= isl_space_set_dim_id(space
, isl_dim_param
, 0, id
);
256 set
= isl_set_universe(space
);
258 v
= PetScan::extract_int(ctx
, il
);
259 set
= isl_set_fix_val(set
, isl_dim_param
, 0, v
);
261 return isl_set_intersect(value
, set
);
264 /* Handle pragmas of the form
266 * #pragma parameter identifier lower_bound
268 * #pragma parameter identifier lower_bound upper_bound
270 * For each such pragma, intersect the context with the set
271 * [identifier] -> { [] : lower_bound <= identifier <= upper_bound }
273 struct PragmaParameterHandler
: public PragmaHandler
{
276 isl_set
*&context_value
;
278 PragmaParameterHandler(Sema
&sema
, isl_set
*&context
,
279 isl_set
*&context_value
) :
280 PragmaHandler("parameter"), sema(sema
), context(context
),
281 context_value(context_value
) {}
283 virtual void HandlePragma(Preprocessor
&PP
,
284 PragmaIntroducer Introducer
,
287 isl_ctx
*ctx
= isl_set_get_ctx(context
);
297 vd
= get_value_decl(sema
, token
);
299 unsupported(PP
, token
.getLocation());
304 if (!token
.isLiteral()) {
305 unsupported(PP
, token
.getLocation());
309 lb
= get_int(token
.getLiteralData());
312 if (token
.isLiteral()) {
314 ub
= get_int(token
.getLiteralData());
315 } else if (token
.isNot(tok::eod
)) {
316 unsupported(PP
, token
.getLocation());
320 id
= isl_id_alloc(ctx
, vd
->getName().str().c_str(), vd
);
321 dim
= isl_space_params_alloc(ctx
, 1);
322 dim
= isl_space_set_dim_id(dim
, isl_dim_param
, 0, id
);
324 set
= isl_set_universe(dim
);
326 set
= isl_set_lower_bound_si(set
, isl_dim_param
, 0, lb
);
328 set
= isl_set_upper_bound_si(set
, isl_dim_param
, 0, ub
);
330 context
= isl_set_intersect(context
, set
);
332 context_value
= extract_initialization(context_value
, vd
);
336 /* Handle pragmas of the form
338 * #pragma pencil independent
340 * For each such pragma, add an entry to the "independent" vector.
342 struct PragmaPencilHandler
: public PragmaHandler
{
343 std::vector
<Independent
> &independent
;
345 PragmaPencilHandler(std::vector
<Independent
> &independent
) :
346 PragmaHandler("pencil"), independent(independent
) {}
348 virtual void HandlePragma(Preprocessor
&PP
,
349 PragmaIntroducer Introducer
,
352 IdentifierInfo
*info
;
355 if (token
.isNot(tok::identifier
))
358 info
= token
.getIdentifierInfo();
359 if (!info
->isStr("independent"))
363 if (token
.isNot(tok::eod
))
366 SourceManager
&SM
= PP
.getSourceManager();
367 SourceLocation sloc
= PencilTok
.getLocation();
368 unsigned line
= SM
.getExpansionLineNumber(sloc
);
369 independent
.push_back(Independent(line
));
373 #ifdef HAVE_TRANSLATELINECOL
375 /* Return a SourceLocation for line "line", column "col" of file "FID".
377 SourceLocation
translateLineCol(SourceManager
&SM
, FileID FID
, unsigned line
,
380 return SM
.translateLineCol(FID
, line
, col
);
385 /* Return a SourceLocation for line "line", column "col" of file "FID".
387 SourceLocation
translateLineCol(SourceManager
&SM
, FileID FID
, unsigned line
,
390 return SM
.getLocation(SM
.getFileEntryForID(FID
), line
, col
);
395 /* List of pairs of #pragma scop and #pragma endscop locations.
398 std::vector
<ScopLoc
> list
;
400 /* Add a new start (#pragma scop) location to the list.
401 * If the last #pragma scop did not have a matching
402 * #pragma endscop then overwrite it.
403 * "start" points to the location of the scop pragma.
405 void add_start(SourceManager
&SM
, SourceLocation start
) {
409 int line
= SM
.getExpansionLineNumber(start
);
410 start
= translateLineCol(SM
, SM
.getFileID(start
), line
, 1);
411 loc
.start_line
= line
;
412 loc
.start
= SM
.getFileOffset(start
);
413 if (list
.size() == 0 || list
[list
.size() - 1].end
!= 0)
416 list
[list
.size() - 1] = loc
;
419 /* Set the end location (#pragma endscop) of the last pair
421 * If there is no such pair of if the end of that pair
422 * is already set, then ignore the spurious #pragma endscop.
423 * "end" points to the location of the endscop pragma.
425 void add_end(SourceManager
&SM
, SourceLocation end
) {
426 if (list
.size() == 0 || list
[list
.size() - 1].end
!= 0)
428 list
[list
.size() - 1].endscop
= end
;
429 int line
= SM
.getExpansionLineNumber(end
);
430 end
= translateLineCol(SM
, SM
.getFileID(end
), line
+ 1, 1);
431 list
[list
.size() - 1].end
= SM
.getFileOffset(end
);
435 /* Handle pragmas of the form
439 * In particular, store the location of the line containing
440 * the pragma in the list "scops".
442 struct PragmaScopHandler
: public PragmaHandler
{
445 PragmaScopHandler(ScopLocList
&scops
) :
446 PragmaHandler("scop"), scops(scops
) {}
448 virtual void HandlePragma(Preprocessor
&PP
,
449 PragmaIntroducer Introducer
,
451 SourceManager
&SM
= PP
.getSourceManager();
452 SourceLocation sloc
= ScopTok
.getLocation();
453 scops
.add_start(SM
, sloc
);
457 /* Handle pragmas of the form
461 * In particular, store the location of the line following the one containing
462 * the pragma in the list "scops".
464 struct PragmaEndScopHandler
: public PragmaHandler
{
467 PragmaEndScopHandler(ScopLocList
&scops
) :
468 PragmaHandler("endscop"), scops(scops
) {}
470 virtual void HandlePragma(Preprocessor
&PP
,
471 PragmaIntroducer Introducer
,
473 SourceManager
&SM
= PP
.getSourceManager();
474 SourceLocation sloc
= EndScopTok
.getLocation();
475 scops
.add_end(SM
, sloc
);
479 /* Handle pragmas of the form
481 * #pragma live-out identifier, identifier, ...
483 * Each identifier on the line is stored in live_out.
485 struct PragmaLiveOutHandler
: public PragmaHandler
{
487 set
<ValueDecl
*> &live_out
;
489 PragmaLiveOutHandler(Sema
&sema
, set
<ValueDecl
*> &live_out
) :
490 PragmaHandler("live"), sema(sema
), live_out(live_out
) {}
492 virtual void HandlePragma(Preprocessor
&PP
,
493 PragmaIntroducer Introducer
,
498 if (token
.isNot(tok::minus
))
501 if (token
.isNot(tok::identifier
) ||
502 !token
.getIdentifierInfo()->isStr("out"))
506 while (token
.isNot(tok::eod
)) {
509 vd
= get_value_decl(sema
, token
);
511 unsupported(PP
, token
.getLocation());
516 if (token
.is(tok::comma
))
522 /* For each array in "scop", set its value_bounds property
523 * based on the information in "value_bounds" and
524 * mark it as live_out if it appears in "live_out".
526 static void update_arrays(struct pet_scop
*scop
,
527 __isl_take isl_union_map
*value_bounds
, set
<ValueDecl
*> &live_out
)
529 set
<ValueDecl
*>::iterator lo_it
;
530 isl_ctx
*ctx
= isl_union_map_get_ctx(value_bounds
);
533 isl_union_map_free(value_bounds
);
537 for (int i
= 0; i
< scop
->n_array
; ++i
) {
542 pet_array
*array
= scop
->arrays
[i
];
544 id
= isl_set_get_tuple_id(array
->extent
);
545 decl
= pet_id_get_decl(id
);
547 space
= isl_space_alloc(ctx
, 0, 0, 1);
548 space
= isl_space_set_tuple_id(space
, isl_dim_in
, id
);
550 bounds
= isl_union_map_extract_map(value_bounds
, space
);
551 if (!isl_map_plain_is_empty(bounds
))
552 array
->value_bounds
= isl_map_range(bounds
);
554 isl_map_free(bounds
);
556 lo_it
= live_out
.find(decl
);
557 if (lo_it
!= live_out
.end())
561 isl_union_map_free(value_bounds
);
564 /* Extract a pet_scop (if any) from each appropriate function.
565 * Each detected scop is passed to "fn".
566 * When autodetecting, at most one scop is extracted from each function.
567 * If "function" is not NULL, then we only extract a pet_scop if the
568 * name of the function matches.
569 * If "autodetect" is false, then we only extract if we have seen
570 * scop and endscop pragmas and if these are situated inside the function
573 struct PetASTConsumer
: public ASTConsumer
{
575 ASTContext
&ast_context
;
576 DiagnosticsEngine
&diags
;
578 std::vector
<Independent
> independent
;
579 const char *function
;
580 pet_options
*options
;
583 isl_set
*context_value
;
584 set
<ValueDecl
*> live_out
;
585 PragmaValueBoundsHandler
*vb_handler
;
586 isl_stat (*fn
)(struct pet_scop
*scop
, void *user
);
590 PetASTConsumer(isl_ctx
*ctx
, Preprocessor
&PP
, ASTContext
&ast_context
,
591 DiagnosticsEngine
&diags
, ScopLocList
&scops
,
592 const char *function
, pet_options
*options
,
593 isl_stat (*fn
)(struct pet_scop
*scop
, void *user
), void *user
) :
594 PP(PP
), ast_context(ast_context
), diags(diags
),
595 scops(scops
), function(function
), options(options
),
597 vb_handler(NULL
), fn(fn
), user(user
), error(false)
600 space
= isl_space_params_alloc(ctx
, 0);
601 context
= isl_set_universe(isl_space_copy(space
));
602 context_value
= isl_set_universe(space
);
606 isl_set_free(context
);
607 isl_set_free(context_value
);
610 void handle_value_bounds(Sema
*sema
) {
611 vb_handler
= new PragmaValueBoundsHandler(ctx
, *sema
);
612 PP
.AddPragmaHandler(vb_handler
);
615 /* Add all pragma handlers to this->PP.
616 * The pencil pragmas are only handled if the pencil option is set.
618 void add_pragma_handlers(Sema
*sema
) {
619 PP
.AddPragmaHandler(new PragmaParameterHandler(*sema
, context
,
621 if (options
->pencil
) {
623 PH
= new PragmaPencilHandler(independent
);
624 PP
.AddPragmaHandler(PH
);
626 handle_value_bounds(sema
);
629 __isl_give isl_union_map
*get_value_bounds() {
630 return isl_union_map_copy(vb_handler
->value_bounds
);
633 /* Pass "scop" to "fn" after performing some postprocessing.
634 * In particular, add the context and value_bounds constraints
635 * speficied through pragmas, add reference identifiers and
636 * reset user pointers on parameters and tuple ids.
638 * If "scop" does not contain any statements and autodetect
639 * is turned on, then skip it.
641 void call_fn(pet_scop
*scop
) {
646 if (diags
.hasErrorOccurred()) {
651 if (options
->autodetect
&& scop
->n_stmt
== 0) {
655 scop
->context
= isl_set_intersect(scop
->context
,
656 isl_set_copy(context
));
657 scop
->context_value
= isl_set_intersect(scop
->context_value
,
658 isl_set_copy(context_value
));
660 update_arrays(scop
, get_value_bounds(), live_out
);
662 scop
= pet_scop_add_ref_ids(scop
);
663 scop
= pet_scop_anonymize(scop
);
665 if (fn(scop
, user
) < 0)
669 /* For each explicitly marked scop (using pragmas),
670 * extract the scop and call "fn" on it if it is inside "fd".
672 void scan_scops(FunctionDecl
*fd
) {
674 vector
<ScopLoc
>::iterator it
;
675 isl_union_map
*vb
= vb_handler
->value_bounds
;
676 SourceManager
&SM
= PP
.getSourceManager();
679 if (scops
.list
.size() == 0)
682 start
= SM
.getFileOffset(begin_loc(fd
));
683 end
= SM
.getFileOffset(end_loc(fd
));
685 for (it
= scops
.list
.begin(); it
!= scops
.list
.end(); ++it
) {
693 PetScan
ps(PP
, ast_context
, fd
, loc
, options
,
694 isl_union_map_copy(vb
), independent
);
700 virtual HandleTopLevelDeclReturn
HandleTopLevelDecl(DeclGroupRef dg
) {
701 DeclGroupRef::iterator it
;
704 return HandleTopLevelDeclContinue
;
706 for (it
= dg
.begin(); it
!= dg
.end(); ++it
) {
707 isl_union_map
*vb
= vb_handler
->value_bounds
;
708 FunctionDecl
*fd
= dyn_cast
<clang::FunctionDecl
>(*it
);
714 fd
->getNameInfo().getAsString() != function
)
716 if (options
->autodetect
) {
719 PetScan
ps(PP
, ast_context
, fd
, loc
, options
,
720 isl_union_map_copy(vb
),
731 return HandleTopLevelDeclContinue
;
735 static const char *ResourceDir
=
736 CLANG_PREFIX
"/lib/clang/" CLANG_VERSION_STRING
;
738 static const char *implicit_functions
[] = {
739 "min", "max", "intMod", "intCeil", "intFloor", "ceild", "floord"
741 static const char *pencil_implicit_functions
[] = {
742 "imin", "umin", "imax", "umax", "__pencil_kill"
745 /* Should "ident" be treated as an implicit function?
746 * If "pencil" is set, then also allow pencil specific builtins.
748 static bool is_implicit(const IdentifierInfo
*ident
, int pencil
)
750 const char *name
= ident
->getNameStart();
751 for (size_t i
= 0; i
< ARRAY_SIZE(implicit_functions
); ++i
)
752 if (!strcmp(name
, implicit_functions
[i
]))
756 for (size_t i
= 0; i
< ARRAY_SIZE(pencil_implicit_functions
); ++i
)
757 if (!strcmp(name
, pencil_implicit_functions
[i
]))
762 /* Ignore implicit function declaration warnings on
763 * "min", "max", "ceild" and "floord" as we detect and handle these
765 * If "pencil" is set, then also ignore them on pencil specific
768 struct MyDiagnosticPrinter
: public TextDiagnosticPrinter
{
769 const DiagnosticOptions
*DiagOpts
;
771 #ifdef HAVE_BASIC_DIAGNOSTICOPTIONS_H
772 MyDiagnosticPrinter(DiagnosticOptions
*DO
, int pencil
) :
773 TextDiagnosticPrinter(llvm::errs(), DO
), pencil(pencil
) {}
774 virtual DiagnosticConsumer
*clone(DiagnosticsEngine
&Diags
) const {
775 return new MyDiagnosticPrinter(&Diags
.getDiagnosticOptions(),
779 MyDiagnosticPrinter(const DiagnosticOptions
&DO
, int pencil
) :
780 DiagOpts(&DO
), TextDiagnosticPrinter(llvm::errs(), DO
),
782 virtual DiagnosticConsumer
*clone(DiagnosticsEngine
&Diags
) const {
783 return new MyDiagnosticPrinter(*DiagOpts
, pencil
);
786 virtual void HandleDiagnostic(DiagnosticsEngine::Level level
,
787 const DiagnosticInfo
&info
) {
788 if (info
.getID() == diag::ext_implicit_function_decl_c99
&&
789 info
.getNumArgs() >= 1 &&
790 info
.getArgKind(0) == DiagnosticsEngine::ak_identifierinfo
&&
791 is_implicit(info
.getArgIdentifier(0), pencil
))
792 /* ignore warning */;
794 TextDiagnosticPrinter::HandleDiagnostic(level
, info
);
800 #ifdef HAVE_CXXISPRODUCTION
801 static Driver
*construct_driver(const char *binary
, DiagnosticsEngine
&Diags
)
803 return new Driver(binary
, llvm::sys::getDefaultTargetTriple(),
804 "", false, false, Diags
);
806 #elif defined(HAVE_ISPRODUCTION)
807 static Driver
*construct_driver(const char *binary
, DiagnosticsEngine
&Diags
)
809 return new Driver(binary
, llvm::sys::getDefaultTargetTriple(),
812 #elif defined(DRIVER_CTOR_TAKES_DEFAULTIMAGENAME)
813 static Driver
*construct_driver(const char *binary
, DiagnosticsEngine
&Diags
)
815 return new Driver(binary
, llvm::sys::getDefaultTargetTriple(),
819 static Driver
*construct_driver(const char *binary
, DiagnosticsEngine
&Diags
)
821 return new Driver(binary
, llvm::sys::getDefaultTargetTriple(), Diags
);
825 namespace clang
{ namespace driver
{ class Job
; } }
827 /* Clang changed its API from 3.5 to 3.6 and once more in 3.7.
828 * We fix this with a simple overloaded function here.
831 static Job
*command(Job
*J
) { return J
; }
832 static Job
*command(Job
&J
) { return &J
; }
833 static Command
*command(Command
&C
) { return &C
; }
836 #ifdef CREATE_FROM_ARGS_TAKES_ARRAYREF
838 /* Call CompilerInvocation::CreateFromArgs with the right arguments.
839 * In this case, an ArrayRef<const char *>.
841 static void create_from_args(CompilerInvocation
&invocation
,
842 const ArgStringList
*args
, DiagnosticsEngine
&Diags
)
844 CompilerInvocation::CreateFromArgs(invocation
, *args
, Diags
);
849 /* Call CompilerInvocation::CreateFromArgs with the right arguments.
850 * In this case, two "const char *" pointers.
852 static void create_from_args(CompilerInvocation
&invocation
,
853 const ArgStringList
*args
, DiagnosticsEngine
&Diags
)
855 CompilerInvocation::CreateFromArgs(invocation
, args
->data() + 1,
856 args
->data() + args
->size(),
862 /* Create a CompilerInvocation object that stores the command line
863 * arguments constructed by the driver.
864 * The arguments are mainly useful for setting up the system include
865 * paths on newer clangs and on some platforms.
867 static CompilerInvocation
*construct_invocation(const char *filename
,
868 DiagnosticsEngine
&Diags
)
870 const char *binary
= CLANG_PREFIX
"/bin/clang";
871 const unique_ptr
<Driver
> driver(construct_driver(binary
, Diags
));
872 std::vector
<const char *> Argv
;
873 Argv
.push_back(binary
);
874 Argv
.push_back(filename
);
875 const unique_ptr
<Compilation
> compilation(
876 driver
->BuildCompilation(llvm::ArrayRef
<const char *>(Argv
)));
877 JobList
&Jobs
= compilation
->getJobs();
881 Command
*cmd
= cast
<Command
>(ClangAPI::command(*Jobs
.begin()));
882 if (strcmp(cmd
->getCreator().getName(), "clang"))
885 const ArgStringList
*args
= &cmd
->getArguments();
887 CompilerInvocation
*invocation
= new CompilerInvocation
;
888 create_from_args(*invocation
, args
, Diags
);
894 static CompilerInvocation
*construct_invocation(const char *filename
,
895 DiagnosticsEngine
&Diags
)
902 #ifdef HAVE_BASIC_DIAGNOSTICOPTIONS_H
904 static MyDiagnosticPrinter
*construct_printer(CompilerInstance
*Clang
,
907 return new MyDiagnosticPrinter(new DiagnosticOptions(), pencil
);
912 static MyDiagnosticPrinter
*construct_printer(CompilerInstance
*Clang
,
915 return new MyDiagnosticPrinter(Clang
->getDiagnosticOpts(), pencil
);
920 #ifdef CREATETARGETINFO_TAKES_SHARED_PTR
922 static TargetInfo
*create_target_info(CompilerInstance
*Clang
,
923 DiagnosticsEngine
&Diags
)
925 shared_ptr
<TargetOptions
> TO
= Clang
->getInvocation().TargetOpts
;
926 TO
->Triple
= llvm::sys::getDefaultTargetTriple();
927 return TargetInfo::CreateTargetInfo(Diags
, TO
);
930 #elif defined(CREATETARGETINFO_TAKES_POINTER)
932 static TargetInfo
*create_target_info(CompilerInstance
*Clang
,
933 DiagnosticsEngine
&Diags
)
935 TargetOptions
&TO
= Clang
->getTargetOpts();
936 TO
.Triple
= llvm::sys::getDefaultTargetTriple();
937 return TargetInfo::CreateTargetInfo(Diags
, &TO
);
942 static TargetInfo
*create_target_info(CompilerInstance
*Clang
,
943 DiagnosticsEngine
&Diags
)
945 TargetOptions
&TO
= Clang
->getTargetOpts();
946 TO
.Triple
= llvm::sys::getDefaultTargetTriple();
947 return TargetInfo::CreateTargetInfo(Diags
, TO
);
952 #ifdef CREATEDIAGNOSTICS_TAKES_ARG
954 static void create_diagnostics(CompilerInstance
*Clang
)
956 Clang
->createDiagnostics(0, NULL
);
961 static void create_diagnostics(CompilerInstance
*Clang
)
963 Clang
->createDiagnostics();
968 #ifdef CREATEPREPROCESSOR_TAKES_TUKIND
970 static void create_preprocessor(CompilerInstance
*Clang
)
972 Clang
->createPreprocessor(TU_Complete
);
977 static void create_preprocessor(CompilerInstance
*Clang
)
979 Clang
->createPreprocessor();
984 #ifdef ADDPATH_TAKES_4_ARGUMENTS
986 void add_path(HeaderSearchOptions
&HSO
, string Path
)
988 HSO
.AddPath(Path
, frontend::Angled
, false, false);
993 void add_path(HeaderSearchOptions
&HSO
, string Path
)
995 HSO
.AddPath(Path
, frontend::Angled
, true, false, false);
1000 #ifdef HAVE_SETMAINFILEID
1002 static void create_main_file_id(SourceManager
&SM
, const FileEntry
*file
)
1004 SM
.setMainFileID(SM
.createFileID(file
, SourceLocation(),
1010 static void create_main_file_id(SourceManager
&SM
, const FileEntry
*file
)
1012 SM
.createMainFileID(file
);
1017 #ifdef SETLANGDEFAULTS_TAKES_5_ARGUMENTS
1019 #include "set_lang_defaults_arg4.h"
1021 static void set_lang_defaults(CompilerInstance
*Clang
)
1023 PreprocessorOptions
&PO
= Clang
->getPreprocessorOpts();
1024 TargetOptions
&TO
= Clang
->getTargetOpts();
1025 llvm::Triple
T(TO
.Triple
);
1026 SETLANGDEFAULTS::setLangDefaults(Clang
->getLangOpts(), IK_C
, T
,
1027 setLangDefaultsArg4(PO
),
1028 LangStandard::lang_unspecified
);
1033 static void set_lang_defaults(CompilerInstance
*Clang
)
1035 CompilerInvocation::setLangDefaults(Clang
->getLangOpts(), IK_C
,
1036 LangStandard::lang_unspecified
);
1041 #ifdef SETINVOCATION_TAKES_SHARED_PTR
1043 static void set_invocation(CompilerInstance
*Clang
,
1044 CompilerInvocation
*invocation
)
1046 Clang
->setInvocation(std::shared_ptr
<CompilerInvocation
>(invocation
));
1051 static void set_invocation(CompilerInstance
*Clang
,
1052 CompilerInvocation
*invocation
)
1054 Clang
->setInvocation(invocation
);
1059 /* Helper function for ignore_error that only gets enabled if T
1060 * (which is either const FileEntry * or llvm::ErrorOr<const FileEntry *>)
1061 * has getError method, i.e., if it is llvm::ErrorOr<const FileEntry *>.
1064 static const FileEntry
*ignore_error_helper(const T obj
, int,
1065 int[1][sizeof(obj
.getError())])
1070 /* Helper function for ignore_error that is always enabled,
1071 * but that only gets selected if the variant above is not enabled,
1072 * i.e., if T is const FileEntry *.
1075 static const FileEntry
*ignore_error_helper(const T obj
, long, void *)
1080 /* Given either a const FileEntry * or a llvm::ErrorOr<const FileEntry *>,
1081 * extract out the const FileEntry *.
1084 static const FileEntry
*ignore_error(const T obj
)
1086 return ignore_error_helper(obj
, 0, NULL
);
1089 /* Return the FileEntry corresponding to the given file name
1090 * in the given compiler instances, ignoring any error.
1092 static const FileEntry
*getFile(CompilerInstance
*Clang
, std::string Filename
)
1094 return ignore_error(Clang
->getFileManager().getFile(Filename
));
1097 /* Return the ownership of "buffer".
1099 * If "buffer" is a pointer, simply return the pointer.
1100 * If "buffer" is a std::unique_ptr, call release() on it.
1101 * Note that std::unique_ptr was not being used back when clang
1102 * was still using llvm::OwningPtr.
1104 static llvm::MemoryBuffer
*release(llvm::MemoryBuffer
*buffer
)
1108 #ifndef HAVE_ADT_OWNINGPTR_H
1109 static llvm::MemoryBuffer
*release(std::unique_ptr
<llvm::MemoryBuffer
> buffer
)
1111 return buffer
.release();
1115 /* Pencil specific predefines.
1117 static const char *pencil_predefines
=
1118 "void __pencil_assume(int assumption);\n"
1119 "#define pencil_access(f) annotate(\"pencil_access(\" #f \")\")\n";
1121 /* Add pet specific predefines to the preprocessor.
1122 * Currently, these are all pencil specific, so they are only
1123 * added if "pencil" is set.
1125 * Include a special "/pet" header and ensure it gets replaced
1126 * by "pencil_predefines" by mapping the "/pet" file to a memory buffer.
1128 static void add_predefines(PreprocessorOptions
&PO
, int pencil
)
1133 PO
.Includes
.push_back("/pet");
1134 PO
.addRemappedFile("/pet",
1135 release(llvm::MemoryBuffer::getMemBuffer(pencil_predefines
)));
1138 /* Do not treat implicit function declaration warnings as errors.
1140 * Only do this if DiagnosticsEngine::setDiagnosticGroupWarningAsError
1141 * is available. In earlier versions of clang, these warnings
1142 * are not treated as errors by default.
1144 #ifdef HAVE_SET_DIAGNOSTIC_GROUP_WARNING_AS_ERROR
1145 static void set_implicit_function_declaration_no_error(DiagnosticsEngine
&Diags
)
1147 Diags
.setDiagnosticGroupWarningAsError("implicit-function-declaration",
1151 static void set_implicit_function_declaration_no_error(DiagnosticsEngine
&Diags
)
1156 /* Extract a pet_scop from each function in the C source file called "filename".
1157 * Each detected scop is passed to "fn".
1158 * If "function" is not NULL, only extract a pet_scop from the function
1160 * If "autodetect" is set, extract any pet_scop we can find.
1161 * Otherwise, extract the pet_scop from the region delimited
1162 * by "scop" and "endscop" pragmas.
1164 * We first set up the clang parser and then try to extract the
1165 * pet_scop from the appropriate function(s) in PetASTConsumer.
1167 static isl_stat
foreach_scop_in_C_source(isl_ctx
*ctx
,
1168 const char *filename
, const char *function
, pet_options
*options
,
1169 isl_stat (*fn
)(struct pet_scop
*scop
, void *user
), void *user
)
1171 CompilerInstance
*Clang
= new CompilerInstance();
1172 create_diagnostics(Clang
);
1173 DiagnosticsEngine
&Diags
= Clang
->getDiagnostics();
1174 Diags
.setSuppressSystemWarnings(true);
1175 set_implicit_function_declaration_no_error(Diags
);
1176 TargetInfo
*target
= create_target_info(Clang
, Diags
);
1177 Clang
->setTarget(target
);
1178 set_lang_defaults(Clang
);
1179 CompilerInvocation
*invocation
= construct_invocation(filename
, Diags
);
1181 set_invocation(Clang
, invocation
);
1182 Diags
.setClient(construct_printer(Clang
, options
->pencil
));
1183 Clang
->createFileManager();
1184 Clang
->createSourceManager(Clang
->getFileManager());
1185 HeaderSearchOptions
&HSO
= Clang
->getHeaderSearchOpts();
1186 HSO
.ResourceDir
= ResourceDir
;
1187 for (int i
= 0; i
< options
->n_path
; ++i
)
1188 add_path(HSO
, options
->paths
[i
]);
1189 PreprocessorOptions
&PO
= Clang
->getPreprocessorOpts();
1190 for (int i
= 0; i
< options
->n_define
; ++i
)
1191 PO
.addMacroDef(options
->defines
[i
]);
1192 add_predefines(PO
, options
->pencil
);
1193 create_preprocessor(Clang
);
1194 Preprocessor
&PP
= Clang
->getPreprocessor();
1195 PP
.getBuiltinInfo().initializeBuiltins(PP
.getIdentifierTable(),
1200 const FileEntry
*file
= getFile(Clang
, filename
);
1202 isl_die(ctx
, isl_error_unknown
, "unable to open file",
1203 do { delete Clang
; return isl_stat_error
; } while (0));
1204 create_main_file_id(Clang
->getSourceManager(), file
);
1206 Clang
->createASTContext();
1207 PetASTConsumer
consumer(ctx
, PP
, Clang
->getASTContext(), Diags
,
1208 scops
, function
, options
, fn
, user
);
1209 Sema
*sema
= new Sema(PP
, Clang
->getASTContext(), consumer
);
1211 if (!options
->autodetect
) {
1212 PP
.AddPragmaHandler(new PragmaScopHandler(scops
));
1213 PP
.AddPragmaHandler(new PragmaEndScopHandler(scops
));
1214 PP
.AddPragmaHandler(new PragmaLiveOutHandler(*sema
,
1215 consumer
.live_out
));
1218 consumer
.add_pragma_handlers(sema
);
1220 Diags
.getClient()->BeginSourceFile(Clang
->getLangOpts(), &PP
);
1222 Diags
.getClient()->EndSourceFile();
1227 return consumer
.error
? isl_stat_error
: isl_stat_ok
;
1230 /* Extract a pet_scop from each function in the C source file called "filename".
1231 * Each detected scop is passed to "fn".
1233 * This wrapper around foreach_scop_in_C_source is mainly used to ensure
1234 * that all objects on the stack (of that function) are destroyed before we
1235 * call llvm_shutdown.
1237 static isl_stat
pet_foreach_scop_in_C_source(isl_ctx
*ctx
,
1238 const char *filename
, const char *function
,
1239 isl_stat (*fn
)(struct pet_scop
*scop
, void *user
), void *user
)
1242 pet_options
*options
;
1243 bool allocated
= false;
1245 options
= isl_ctx_peek_pet_options(ctx
);
1247 options
= pet_options_new_with_defaults();
1251 r
= foreach_scop_in_C_source(ctx
, filename
, function
, options
,
1253 llvm::llvm_shutdown();
1256 pet_options_free(options
);
1261 /* Store "scop" into the address pointed to by "user".
1262 * Return -1 to indicate that we are not interested in any further scops.
1263 * This function should therefore not be called a second call
1264 * so in principle there is no need to check if we have already set *user.
1266 static isl_stat
set_first_scop(pet_scop
*scop
, void *user
)
1268 pet_scop
**p
= (pet_scop
**) user
;
1273 pet_scop_free(scop
);
1275 return isl_stat_error
;
1278 /* Extract a pet_scop from the C source file called "filename".
1279 * If "function" is not NULL, extract the pet_scop from the function
1282 * We start extracting scops from every function and then abort
1283 * as soon as we have extracted one scop.
1285 struct pet_scop
*pet_scop_extract_from_C_source(isl_ctx
*ctx
,
1286 const char *filename
, const char *function
)
1288 pet_scop
*scop
= NULL
;
1290 pet_foreach_scop_in_C_source(ctx
, filename
, function
,
1291 &set_first_scop
, &scop
);
1296 /* Internal data structure for pet_transform_C_source
1298 * transform is the function that should be called to print a scop
1299 * in is the input source file
1300 * out is the output source file
1301 * end is the offset of the end of the previous scop (zero if we have not
1302 * found any scop yet)
1303 * p is a printer that prints to out.
1305 struct pet_transform_data
{
1306 __isl_give isl_printer
*(*transform
)(__isl_take isl_printer
*p
,
1307 struct pet_scop
*scop
, void *user
);
1316 /* This function is called each time a scop is detected.
1318 * We first copy the input text code from the end of the previous scop
1319 * until the start of "scop" and then print the scop itself through
1320 * a call to data->transform. We set up the printer to print
1321 * the transformed code with the same (initial) indentation as
1322 * the original code.
1323 * Finally, we keep track of the end of "scop" so that we can
1324 * continue copying when we find the next scop.
1326 * Before calling data->transform, we store a pointer to the original
1327 * input file in the extended scop in case the user wants to call
1328 * pet_scop_print_original from the callback.
1330 static isl_stat
pet_transform(struct pet_scop
*scop
, void *user
)
1332 struct pet_transform_data
*data
= (struct pet_transform_data
*) user
;
1336 return isl_stat_error
;
1337 start
= pet_loc_get_start(scop
->loc
);
1338 if (copy(data
->in
, data
->out
, data
->end
, start
) < 0)
1340 data
->end
= pet_loc_get_end(scop
->loc
);
1341 scop
= pet_scop_set_input_file(scop
, data
->in
);
1342 data
->p
= isl_printer_set_indent_prefix(data
->p
,
1343 pet_loc_get_indent(scop
->loc
));
1344 data
->p
= data
->transform(data
->p
, scop
, data
->user
);
1346 return isl_stat_error
;
1349 pet_scop_free(scop
);
1350 return isl_stat_error
;
1353 /* Transform the C source file "input" by rewriting each scop
1354 * through a call to "transform".
1355 * When autodetecting scops, at most one scop per function is rewritten.
1356 * The transformed C code is written to "output".
1358 * For each scop we find, we first copy the input text code
1359 * from the end of the previous scop (or the beginning of the file
1360 * in case of the first scop) until the start of the scop
1361 * and then print the scop itself through a call to "transform".
1362 * At the end we copy everything from the end of the final scop
1363 * until the end of the input file to "output".
1365 int pet_transform_C_source(isl_ctx
*ctx
, const char *input
, FILE *out
,
1366 __isl_give isl_printer
*(*transform
)(__isl_take isl_printer
*p
,
1367 struct pet_scop
*scop
, void *user
), void *user
)
1369 struct pet_transform_data data
;
1374 if (input
&& strcmp(input
, "-")) {
1375 data
.in
= fopen(input
, "r");
1377 isl_die(ctx
, isl_error_unknown
, "unable to open file",
1381 data
.p
= isl_printer_to_file(ctx
, data
.out
);
1382 data
.p
= isl_printer_set_output_format(data
.p
, ISL_FORMAT_C
);
1384 data
.transform
= transform
;
1387 r
= pet_foreach_scop_in_C_source(ctx
, input
, NULL
,
1388 &pet_transform
, &data
);
1390 isl_printer_free(data
.p
);
1393 if (r
== 0 && copy(data
.in
, data
.out
, data
.end
, -1) < 0)
1396 if (data
.in
!= stdin
)