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.
11  *
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.
16  *
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.
28  *
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  */
34 
35 #include "config.h"
36 #undef PACKAGE
37 
38 #include <stdlib.h>
39 #include <map>
40 #include <vector>
41 #include <iostream>
42 #ifdef HAVE_ADT_OWNINGPTR_H
43 #include <llvm/ADT/OwningPtr.h>
44 #else
45 #include <memory>
46 #endif
47 #ifdef HAVE_LLVM_OPTION_ARG_H
48 #include <llvm/Option/Arg.h>
49 #endif
50 #include <llvm/Support/raw_ostream.h>
51 #include <llvm/Support/ManagedStatic.h>
52 #include <llvm/Support/Host.h>
53 #include <clang/Basic/Version.h>
54 #include <clang/Basic/Builtins.h>
55 #include <clang/Basic/FileSystemOptions.h>
56 #include <clang/Basic/FileManager.h>
57 #include <clang/Basic/TargetOptions.h>
58 #include <clang/Basic/TargetInfo.h>
59 #include <clang/Driver/Compilation.h>
60 #include <clang/Driver/Driver.h>
61 #include <clang/Driver/Tool.h>
62 #include <clang/Frontend/CompilerInstance.h>
63 #include <clang/Frontend/CompilerInvocation.h>
64 #ifdef HAVE_BASIC_DIAGNOSTICOPTIONS_H
65 #include <clang/Basic/DiagnosticOptions.h>
66 #else
67 #include <clang/Frontend/DiagnosticOptions.h>
68 #endif
69 #include <clang/Frontend/TextDiagnosticPrinter.h>
70 #ifdef HAVE_LEX_HEADERSEARCHOPTIONS_H
71 #include <clang/Lex/HeaderSearchOptions.h>
72 #else
73 #include <clang/Frontend/HeaderSearchOptions.h>
74 #endif
75 #ifdef HAVE_CLANG_BASIC_LANGSTANDARD_H
76 #include <clang/Basic/LangStandard.h>
77 #else
78 #include <clang/Frontend/LangStandard.h>
79 #endif
80 #ifdef HAVE_LEX_PREPROCESSOROPTIONS_H
81 #include <clang/Lex/PreprocessorOptions.h>
82 #else
83 #include <clang/Frontend/PreprocessorOptions.h>
84 #endif
85 #include <clang/Frontend/FrontendOptions.h>
86 #include <clang/Frontend/Utils.h>
87 #include <clang/Lex/HeaderSearch.h>
88 #include <clang/Lex/Preprocessor.h>
89 #include <clang/Lex/Pragma.h>
90 #include <clang/AST/ASTContext.h>
91 #include <clang/AST/ASTConsumer.h>
92 #include <clang/Sema/Sema.h>
93 #include <clang/Sema/SemaDiagnostic.h>
94 #include <clang/Parse/Parser.h>
95 #include <clang/Parse/ParseAST.h>
96 
97 #include <isl/ctx.h>
98 #include <isl/constraint.h>
99 
100 #include <pet.h>
101 
102 #include "clang_compatibility.h"
103 #include "id.h"
104 #include "options.h"
105 #include "scan.h"
106 #include "print.h"
107 
108 #define ARRAY_SIZE(array) (sizeof(array)/sizeof(*array))
109 
110 using namespace std;
111 using namespace clang;
112 using namespace clang::driver;
113 #ifdef HAVE_LLVM_OPTION_ARG_H
114 using namespace llvm::opt;
115 #endif
116 
117 #ifdef HAVE_ADT_OWNINGPTR_H
118 #define unique_ptr	llvm::OwningPtr
119 #endif
120 
121 /* Called if we found something we didn't expect in one of the pragmas.
122  * We'll provide more informative warnings later.
123  */
unsupported(Preprocessor & PP,SourceLocation loc)124 static void unsupported(Preprocessor &PP, SourceLocation loc)
125 {
126 	DiagnosticsEngine &diag = PP.getDiagnostics();
127 	unsigned id = diag.getCustomDiagID(DiagnosticsEngine::Warning,
128 					   "unsupported");
129 	DiagnosticBuilder B = diag.Report(loc, id);
130 }
131 
get_int(const char * s)132 static int get_int(const char *s)
133 {
134 	return s[0] == '"' ? atoi(s + 1) : atoi(s);
135 }
136 
get_value_decl(Sema & sema,Token & token)137 static ValueDecl *get_value_decl(Sema &sema, Token &token)
138 {
139 	IdentifierInfo *name;
140 	Decl *decl;
141 
142 	if (token.isNot(tok::identifier))
143 		return NULL;
144 
145 	name = token.getIdentifierInfo();
146 	decl = sema.LookupSingleName(sema.TUScope, name,
147 				token.getLocation(), Sema::LookupOrdinaryName);
148 	return decl ? cast_or_null<ValueDecl>(decl) : NULL;
149 }
150 
151 /* Handle pragmas of the form
152  *
153  *	#pragma value_bounds identifier lower_bound upper_bound
154  *
155  * For each such pragma, add a mapping
156  *	{ identifier[] -> [i] : lower_bound <= i <= upper_bound }
157  * to value_bounds.
158  */
159 struct PragmaValueBoundsHandler : public PragmaHandler {
160 	Sema &sema;
161 	isl_ctx *ctx;
162 	isl_union_map *value_bounds;
163 
PragmaValueBoundsHandlerPragmaValueBoundsHandler164 	PragmaValueBoundsHandler(isl_ctx *ctx, Sema &sema) :
165 	    PragmaHandler("value_bounds"), sema(sema), ctx(ctx) {
166 		isl_space *space = isl_space_params_alloc(ctx, 0);
167 		value_bounds = isl_union_map_empty(space);
168 	}
169 
~PragmaValueBoundsHandlerPragmaValueBoundsHandler170 	~PragmaValueBoundsHandler() {
171 		isl_union_map_free(value_bounds);
172 	}
173 
HandlePragmaPragmaValueBoundsHandler174 	virtual void HandlePragma(Preprocessor &PP,
175 				  PragmaIntroducer Introducer,
176 				  Token &ScopTok) {
177 		isl_id *id;
178 		isl_space *dim;
179 		isl_map *map;
180 		ValueDecl *vd;
181 		Token token;
182 		int lb;
183 		int ub;
184 
185 		PP.Lex(token);
186 		vd = get_value_decl(sema, token);
187 		if (!vd) {
188 			unsupported(PP, token.getLocation());
189 			return;
190 		}
191 
192 		PP.Lex(token);
193 		if (!token.isLiteral()) {
194 			unsupported(PP, token.getLocation());
195 			return;
196 		}
197 
198 		lb = get_int(token.getLiteralData());
199 
200 		PP.Lex(token);
201 		if (!token.isLiteral()) {
202 			unsupported(PP, token.getLocation());
203 			return;
204 		}
205 
206 		ub = get_int(token.getLiteralData());
207 
208 		dim = isl_space_alloc(ctx, 0, 0, 1);
209 		map = isl_map_universe(dim);
210 		map = isl_map_lower_bound_si(map, isl_dim_out, 0, lb);
211 		map = isl_map_upper_bound_si(map, isl_dim_out, 0, ub);
212 		id = isl_id_alloc(ctx, vd->getName().str().c_str(), vd);
213 		map = isl_map_set_tuple_id(map, isl_dim_in, id);
214 
215 		value_bounds = isl_union_map_add_map(value_bounds, map);
216 	}
217 };
218 
219 /* Given a variable declaration, check if it has an integer initializer
220  * and if so, add a parameter corresponding to the variable to "value"
221  * with its value fixed to the integer initializer and return the result.
222  */
extract_initialization(__isl_take isl_set * value,ValueDecl * decl)223 static __isl_give isl_set *extract_initialization(__isl_take isl_set *value,
224 	ValueDecl *decl)
225 {
226 	VarDecl *vd;
227 	Expr *expr;
228 	IntegerLiteral *il;
229 	isl_val *v;
230 	isl_ctx *ctx;
231 	isl_id *id;
232 	isl_space *space;
233 	isl_set *set;
234 
235 	vd = cast<VarDecl>(decl);
236 	if (!vd)
237 		return value;
238 	if (!vd->getType()->isIntegerType())
239 		return value;
240 	expr = vd->getInit();
241 	if (!expr)
242 		return value;
243 	il = cast<IntegerLiteral>(expr);
244 	if (!il)
245 		return value;
246 
247 	ctx = isl_set_get_ctx(value);
248 	id = isl_id_alloc(ctx, vd->getName().str().c_str(), vd);
249 	space = isl_space_params_alloc(ctx, 1);
250 	space = isl_space_set_dim_id(space, isl_dim_param, 0, id);
251 	set = isl_set_universe(space);
252 
253 	v = PetScan::extract_int(ctx, il);
254 	set = isl_set_fix_val(set, isl_dim_param, 0, v);
255 
256 	return isl_set_intersect(value, set);
257 }
258 
259 /* Handle pragmas of the form
260  *
261  *	#pragma parameter identifier lower_bound
262  * and
263  *	#pragma parameter identifier lower_bound upper_bound
264  *
265  * For each such pragma, intersect the context with the set
266  * [identifier] -> { [] : lower_bound <= identifier <= upper_bound }
267  */
268 struct PragmaParameterHandler : public PragmaHandler {
269 	Sema &sema;
270 	isl_set *&context;
271 	isl_set *&context_value;
272 
PragmaParameterHandlerPragmaParameterHandler273 	PragmaParameterHandler(Sema &sema, isl_set *&context,
274 		isl_set *&context_value) :
275 		PragmaHandler("parameter"), sema(sema), context(context),
276 		context_value(context_value) {}
277 
HandlePragmaPragmaParameterHandler278 	virtual void HandlePragma(Preprocessor &PP,
279 				  PragmaIntroducer Introducer,
280 				  Token &ScopTok) {
281 		isl_id *id;
282 		isl_ctx *ctx = isl_set_get_ctx(context);
283 		isl_space *dim;
284 		isl_set *set;
285 		ValueDecl *vd;
286 		Token token;
287 		int lb;
288 		int ub;
289 		bool has_ub = false;
290 
291 		PP.Lex(token);
292 		vd = get_value_decl(sema, token);
293 		if (!vd) {
294 			unsupported(PP, token.getLocation());
295 			return;
296 		}
297 
298 		PP.Lex(token);
299 		if (!token.isLiteral()) {
300 			unsupported(PP, token.getLocation());
301 			return;
302 		}
303 
304 		lb = get_int(token.getLiteralData());
305 
306 		PP.Lex(token);
307 		if (token.isLiteral()) {
308 			has_ub = true;
309 			ub = get_int(token.getLiteralData());
310 		} else if (token.isNot(tok::eod)) {
311 			unsupported(PP, token.getLocation());
312 			return;
313 		}
314 
315 		id = isl_id_alloc(ctx, vd->getName().str().c_str(), vd);
316 		dim = isl_space_params_alloc(ctx, 1);
317 		dim = isl_space_set_dim_id(dim, isl_dim_param, 0, id);
318 
319 		set = isl_set_universe(dim);
320 
321 		set = isl_set_lower_bound_si(set, isl_dim_param, 0, lb);
322 		if (has_ub)
323 			set = isl_set_upper_bound_si(set, isl_dim_param, 0, ub);
324 
325 		context = isl_set_intersect(context, set);
326 
327 		context_value = extract_initialization(context_value, vd);
328 	}
329 };
330 
331 /* Handle pragmas of the form
332  *
333  *	#pragma pencil independent
334  *
335  * For each such pragma, add an entry to the "independent" vector.
336  */
337 struct PragmaPencilHandler : public PragmaHandler {
338 	std::vector<Independent> &independent;
339 
PragmaPencilHandlerPragmaPencilHandler340 	PragmaPencilHandler(std::vector<Independent> &independent) :
341 		PragmaHandler("pencil"), independent(independent) {}
342 
HandlePragmaPragmaPencilHandler343 	virtual void HandlePragma(Preprocessor &PP,
344 				  PragmaIntroducer Introducer,
345 				  Token &PencilTok) {
346 		Token token;
347 		IdentifierInfo *info;
348 
349 		PP.Lex(token);
350 		if (token.isNot(tok::identifier))
351 			return;
352 
353 		info = token.getIdentifierInfo();
354 		if (!info->isStr("independent"))
355 			return;
356 
357 		PP.Lex(token);
358 		if (token.isNot(tok::eod))
359 			return;
360 
361 		SourceManager &SM = PP.getSourceManager();
362 		SourceLocation sloc = PencilTok.getLocation();
363 		unsigned line = SM.getExpansionLineNumber(sloc);
364 		independent.push_back(Independent(line));
365 	}
366 };
367 
368 #ifdef HAVE_TRANSLATELINECOL
369 
370 /* Return a SourceLocation for line "line", column "col" of file "FID".
371  */
translateLineCol(SourceManager & SM,FileID FID,unsigned line,unsigned col)372 SourceLocation translateLineCol(SourceManager &SM, FileID FID, unsigned line,
373 	unsigned col)
374 {
375 	return SM.translateLineCol(FID, line, col);
376 }
377 
378 #else
379 
380 /* Return a SourceLocation for line "line", column "col" of file "FID".
381  */
translateLineCol(SourceManager & SM,FileID FID,unsigned line,unsigned col)382 SourceLocation translateLineCol(SourceManager &SM, FileID FID, unsigned line,
383 	unsigned col)
384 {
385 	return SM.getLocation(SM.getFileEntryForID(FID), line, col);
386 }
387 
388 #endif
389 
390 /* List of pairs of #pragma scop and #pragma endscop locations.
391  */
392 struct ScopLocList {
393 	std::vector<ScopLoc> list;
394 
395 	/* Add a new start (#pragma scop) location to the list.
396 	 * If the last #pragma scop did not have a matching
397 	 * #pragma endscop then overwrite it.
398 	 * "start" points to the location of the scop pragma.
399 	 */
add_startScopLocList400 	void add_start(SourceManager &SM, SourceLocation start) {
401 		ScopLoc loc;
402 
403 		loc.scop = start;
404 		int line = SM.getExpansionLineNumber(start);
405 		start = translateLineCol(SM, SM.getFileID(start), line, 1);
406 		loc.start_line = line;
407 		loc.start = SM.getFileOffset(start);
408 		if (list.size() == 0 || list[list.size() - 1].end != 0)
409 			list.push_back(loc);
410 		else
411 			list[list.size() - 1] = loc;
412 	}
413 
414 	/* Set the end location (#pragma endscop) of the last pair
415 	 * in the list.
416 	 * If there is no such pair of if the end of that pair
417 	 * is already set, then ignore the spurious #pragma endscop.
418 	 * "end" points to the location of the endscop pragma.
419 	 */
add_endScopLocList420 	void add_end(SourceManager &SM, SourceLocation end) {
421 		if (list.size() == 0 || list[list.size() - 1].end != 0)
422 			return;
423 		list[list.size() - 1].endscop = end;
424 		int line = SM.getExpansionLineNumber(end);
425 		end = translateLineCol(SM, SM.getFileID(end), line + 1, 1);
426 		list[list.size() - 1].end = SM.getFileOffset(end);
427 	}
428 };
429 
430 /* Handle pragmas of the form
431  *
432  *	#pragma scop
433  *
434  * In particular, store the location of the line containing
435  * the pragma in the list "scops".
436  */
437 struct PragmaScopHandler : public PragmaHandler {
438 	ScopLocList &scops;
439 
PragmaScopHandlerPragmaScopHandler440 	PragmaScopHandler(ScopLocList &scops) :
441 		PragmaHandler("scop"), scops(scops) {}
442 
HandlePragmaPragmaScopHandler443 	virtual void HandlePragma(Preprocessor &PP,
444 				  PragmaIntroducer Introducer,
445 				  Token &ScopTok) {
446 		SourceManager &SM = PP.getSourceManager();
447 		SourceLocation sloc = ScopTok.getLocation();
448 		scops.add_start(SM, sloc);
449 	}
450 };
451 
452 /* Handle pragmas of the form
453  *
454  *	#pragma endscop
455  *
456  * In particular, store the location of the line following the one containing
457  * the pragma in the list "scops".
458  */
459 struct PragmaEndScopHandler : public PragmaHandler {
460 	ScopLocList &scops;
461 
PragmaEndScopHandlerPragmaEndScopHandler462 	PragmaEndScopHandler(ScopLocList &scops) :
463 		PragmaHandler("endscop"), scops(scops) {}
464 
HandlePragmaPragmaEndScopHandler465 	virtual void HandlePragma(Preprocessor &PP,
466 				  PragmaIntroducer Introducer,
467 				  Token &EndScopTok) {
468 		SourceManager &SM = PP.getSourceManager();
469 		SourceLocation sloc = EndScopTok.getLocation();
470 		scops.add_end(SM, sloc);
471 	}
472 };
473 
474 /* Handle pragmas of the form
475  *
476  *	#pragma live-out identifier, identifier, ...
477  *
478  * Each identifier on the line is stored in live_out.
479  */
480 struct PragmaLiveOutHandler : public PragmaHandler {
481 	Sema &sema;
482 	set<ValueDecl *> &live_out;
483 
PragmaLiveOutHandlerPragmaLiveOutHandler484 	PragmaLiveOutHandler(Sema &sema, set<ValueDecl *> &live_out) :
485 		PragmaHandler("live"), sema(sema), live_out(live_out) {}
486 
HandlePragmaPragmaLiveOutHandler487 	virtual void HandlePragma(Preprocessor &PP,
488 				  PragmaIntroducer Introducer,
489 				  Token &ScopTok) {
490 		Token token;
491 
492 		PP.Lex(token);
493 		if (token.isNot(tok::minus))
494 			return;
495 		PP.Lex(token);
496 		if (token.isNot(tok::identifier) ||
497 		    !token.getIdentifierInfo()->isStr("out"))
498 			return;
499 
500 		PP.Lex(token);
501 		while (token.isNot(tok::eod)) {
502 			ValueDecl *vd;
503 
504 			vd = get_value_decl(sema, token);
505 			if (!vd) {
506 				unsupported(PP, token.getLocation());
507 				return;
508 			}
509 			live_out.insert(vd);
510 			PP.Lex(token);
511 			if (token.is(tok::comma))
512 				PP.Lex(token);
513 		}
514 	}
515 };
516 
517 /* For each array in "scop", set its value_bounds property
518  * based on the information in "value_bounds" and
519  * mark it as live_out if it appears in "live_out".
520  */
update_arrays(struct pet_scop * scop,__isl_take isl_union_map * value_bounds,set<ValueDecl * > & live_out)521 static void update_arrays(struct pet_scop *scop,
522 	__isl_take isl_union_map *value_bounds, set<ValueDecl *> &live_out)
523 {
524 	set<ValueDecl *>::iterator lo_it;
525 	isl_ctx *ctx = isl_union_map_get_ctx(value_bounds);
526 
527 	if (!scop) {
528 		isl_union_map_free(value_bounds);
529 		return;
530 	}
531 
532 	for (int i = 0; i < scop->n_array; ++i) {
533 		isl_id *id;
534 		isl_space *space;
535 		isl_map *bounds;
536 		ValueDecl *decl;
537 		pet_array *array = scop->arrays[i];
538 
539 		id = isl_set_get_tuple_id(array->extent);
540 		decl = pet_id_get_decl(id);
541 
542 		space = isl_space_alloc(ctx, 0, 0, 1);
543 		space = isl_space_set_tuple_id(space, isl_dim_in, id);
544 
545 		bounds = isl_union_map_extract_map(value_bounds, space);
546 		if (!isl_map_plain_is_empty(bounds))
547 			array->value_bounds = isl_map_range(bounds);
548 		else
549 			isl_map_free(bounds);
550 
551 		lo_it = live_out.find(decl);
552 		if (lo_it != live_out.end())
553 			array->live_out = 1;
554 	}
555 
556 	isl_union_map_free(value_bounds);
557 }
558 
559 /* Extract a pet_scop (if any) from each appropriate function.
560  * Each detected scop is passed to "fn".
561  * When autodetecting, at most one scop is extracted from each function.
562  * If "function" is not NULL, then we only extract a pet_scop if the
563  * name of the function matches.
564  * If "autodetect" is false, then we only extract if we have seen
565  * scop and endscop pragmas and if these are situated inside the function
566  * body.
567  */
568 struct PetASTConsumer : public ASTConsumer {
569 	Preprocessor &PP;
570 	ASTContext &ast_context;
571 	DiagnosticsEngine &diags;
572 	ScopLocList &scops;
573 	std::vector<Independent> independent;
574 	const char *function;
575 	pet_options *options;
576 	isl_ctx *ctx;
577 	isl_set *context;
578 	isl_set *context_value;
579 	set<ValueDecl *> live_out;
580 	PragmaValueBoundsHandler *vb_handler;
581 	isl_stat (*fn)(struct pet_scop *scop, void *user);
582 	void *user;
583 	bool error;
584 
PetASTConsumerPetASTConsumer585 	PetASTConsumer(isl_ctx *ctx, Preprocessor &PP, ASTContext &ast_context,
586 		DiagnosticsEngine &diags, ScopLocList &scops,
587 		const char *function, pet_options *options,
588 		isl_stat (*fn)(struct pet_scop *scop, void *user), void *user) :
589 		PP(PP), ast_context(ast_context), diags(diags),
590 		scops(scops), function(function), options(options),
591 		ctx(ctx),
592 		vb_handler(NULL), fn(fn), user(user), error(false)
593 	{
594 		isl_space *space;
595 		space = isl_space_params_alloc(ctx, 0);
596 		context = isl_set_universe(isl_space_copy(space));
597 		context_value = isl_set_universe(space);
598 	}
599 
~PetASTConsumerPetASTConsumer600 	~PetASTConsumer() {
601 		isl_set_free(context);
602 		isl_set_free(context_value);
603 	}
604 
handle_value_boundsPetASTConsumer605 	void handle_value_bounds(Sema *sema) {
606 		vb_handler = new PragmaValueBoundsHandler(ctx, *sema);
607 		PP.AddPragmaHandler(vb_handler);
608 	}
609 
610 	/* Add all pragma handlers to this->PP.
611 	 * The pencil pragmas are only handled if the pencil option is set.
612 	 */
add_pragma_handlersPetASTConsumer613 	void add_pragma_handlers(Sema *sema) {
614 		PP.AddPragmaHandler(new PragmaParameterHandler(*sema, context,
615 								context_value));
616 		if (options->pencil) {
617 			PragmaHandler *PH;
618 			PH = new PragmaPencilHandler(independent);
619 			PP.AddPragmaHandler(PH);
620 		}
621 		handle_value_bounds(sema);
622 	}
623 
get_value_boundsPetASTConsumer624 	__isl_give isl_union_map *get_value_bounds() {
625 		return isl_union_map_copy(vb_handler->value_bounds);
626 	}
627 
628 	/* Pass "scop" to "fn" after performing some postprocessing.
629 	 * In particular, add the context and value_bounds constraints
630 	 * speficied through pragmas, add reference identifiers and
631 	 * reset user pointers on parameters and tuple ids.
632 	 *
633 	 * If "scop" does not contain any statements and autodetect
634 	 * is turned on, then skip it.
635 	 */
call_fnPetASTConsumer636 	void call_fn(pet_scop *scop) {
637 		if (!scop) {
638 			error = true;
639 			return;
640 		}
641 		if (diags.hasErrorOccurred()) {
642 			error = true;
643 			pet_scop_free(scop);
644 			return;
645 		}
646 		if (options->autodetect && scop->n_stmt == 0) {
647 			pet_scop_free(scop);
648 			return;
649 		}
650 		scop->context = isl_set_intersect(scop->context,
651 						isl_set_copy(context));
652 		scop->context_value = isl_set_intersect(scop->context_value,
653 						isl_set_copy(context_value));
654 
655 		update_arrays(scop, get_value_bounds(), live_out);
656 
657 		scop = pet_scop_add_ref_ids(scop);
658 		scop = pet_scop_anonymize(scop);
659 
660 		if (fn(scop, user) < 0)
661 			error = true;
662 	}
663 
664 	/* For each explicitly marked scop (using pragmas),
665 	 * extract the scop and call "fn" on it if it is inside "fd".
666 	 */
scan_scopsPetASTConsumer667 	void scan_scops(FunctionDecl *fd) {
668 		unsigned start, end;
669 		vector<ScopLoc>::iterator it;
670 		isl_union_map *vb = vb_handler->value_bounds;
671 		SourceManager &SM = PP.getSourceManager();
672 		pet_scop *scop;
673 
674 		if (scops.list.size() == 0)
675 			return;
676 
677 		start = SM.getFileOffset(begin_loc(fd));
678 		end = SM.getFileOffset(end_loc(fd));
679 
680 		for (it = scops.list.begin(); it != scops.list.end(); ++it) {
681 			ScopLoc loc = *it;
682 			if (!loc.end)
683 				continue;
684 			if (start > loc.end)
685 				continue;
686 			if (end < loc.start)
687 				continue;
688 			PetScan ps(PP, ast_context, fd, loc, options,
689 				    isl_union_map_copy(vb), independent);
690 			scop = ps.scan(fd);
691 			call_fn(scop);
692 		}
693 	}
694 
HandleTopLevelDeclPetASTConsumer695 	virtual HandleTopLevelDeclReturn HandleTopLevelDecl(DeclGroupRef dg) {
696 		DeclGroupRef::iterator it;
697 
698 		if (error)
699 			return HandleTopLevelDeclContinue;
700 
701 		for (it = dg.begin(); it != dg.end(); ++it) {
702 			isl_union_map *vb = vb_handler->value_bounds;
703 			FunctionDecl *fd = dyn_cast<clang::FunctionDecl>(*it);
704 			if (!fd)
705 				continue;
706 			if (!fd->hasBody())
707 				continue;
708 			if (function &&
709 			    fd->getNameInfo().getAsString() != function)
710 				continue;
711 			if (options->autodetect) {
712 				ScopLoc loc;
713 				pet_scop *scop;
714 				PetScan ps(PP, ast_context, fd, loc, options,
715 					    isl_union_map_copy(vb),
716 					    independent);
717 				scop = ps.scan(fd);
718 				if (!scop)
719 					continue;
720 				call_fn(scop);
721 				continue;
722 			}
723 			scan_scops(fd);
724 		}
725 
726 		return HandleTopLevelDeclContinue;
727 	}
728 };
729 
730 static const char *ResourceDir =
731 	CLANG_PREFIX "/lib/clang/" CLANG_VERSION_STRING;
732 
733 static const char *implicit_functions[] = {
734 	"min", "max", "intMod", "intCeil", "intFloor", "ceild", "floord"
735 };
736 static const char *pencil_implicit_functions[] = {
737 	"imin", "umin", "imax", "umax", "__pencil_kill"
738 };
739 
740 /* Should "ident" be treated as an implicit function?
741  * If "pencil" is set, then also allow pencil specific builtins.
742  */
is_implicit(const IdentifierInfo * ident,int pencil)743 static bool is_implicit(const IdentifierInfo *ident, int pencil)
744 {
745 	const char *name = ident->getNameStart();
746 	for (size_t i = 0; i < ARRAY_SIZE(implicit_functions); ++i)
747 		if (!strcmp(name, implicit_functions[i]))
748 			return true;
749 	if (!pencil)
750 		return false;
751 	for (size_t i = 0; i < ARRAY_SIZE(pencil_implicit_functions); ++i)
752 		if (!strcmp(name, pencil_implicit_functions[i]))
753 			return true;
754 	return false;
755 }
756 
757 /* Ignore implicit function declaration warnings on
758  * "min", "max", "ceild" and "floord" as we detect and handle these
759  * in PetScan.
760  * If "pencil" is set, then also ignore them on pencil specific
761  * builtins.
762  */
763 struct MyDiagnosticPrinter : public TextDiagnosticPrinter {
764 	const DiagnosticOptions *DiagOpts;
765 	int pencil;
766 #ifdef HAVE_BASIC_DIAGNOSTICOPTIONS_H
MyDiagnosticPrinterMyDiagnosticPrinter767 	MyDiagnosticPrinter(DiagnosticOptions *DO, int pencil) :
768 		TextDiagnosticPrinter(llvm::errs(), DO), pencil(pencil) {}
cloneMyDiagnosticPrinter769 	virtual DiagnosticConsumer *clone(DiagnosticsEngine &Diags) const {
770 		return new MyDiagnosticPrinter(&Diags.getDiagnosticOptions(),
771 						pencil);
772 	}
773 #else
MyDiagnosticPrinterMyDiagnosticPrinter774 	MyDiagnosticPrinter(const DiagnosticOptions &DO, int pencil) :
775 		DiagOpts(&DO), TextDiagnosticPrinter(llvm::errs(), DO),
776 		pencil(pencil) {}
cloneMyDiagnosticPrinter777 	virtual DiagnosticConsumer *clone(DiagnosticsEngine &Diags) const {
778 		return new MyDiagnosticPrinter(*DiagOpts, pencil);
779 	}
780 #endif
HandleDiagnosticMyDiagnosticPrinter781 	virtual void HandleDiagnostic(DiagnosticsEngine::Level level,
782 					const DiagnosticInfo &info) {
783 		if (info.getID() == diag::ext_implicit_function_decl &&
784 		    info.getNumArgs() >= 1 &&
785 		    info.getArgKind(0) == DiagnosticsEngine::ak_identifierinfo &&
786 		    is_implicit(info.getArgIdentifier(0), pencil))
787 			/* ignore warning */;
788 		else
789 			TextDiagnosticPrinter::HandleDiagnostic(level, info);
790 	}
791 };
792 
793 #ifdef USE_ARRAYREF
794 
795 #ifdef HAVE_CXXISPRODUCTION
construct_driver(const char * binary,DiagnosticsEngine & Diags)796 static Driver *construct_driver(const char *binary, DiagnosticsEngine &Diags)
797 {
798 	return new Driver(binary, llvm::sys::getDefaultTargetTriple(),
799 			    "", false, false, Diags);
800 }
801 #elif defined(HAVE_ISPRODUCTION)
construct_driver(const char * binary,DiagnosticsEngine & Diags)802 static Driver *construct_driver(const char *binary, DiagnosticsEngine &Diags)
803 {
804 	return new Driver(binary, llvm::sys::getDefaultTargetTriple(),
805 			    "", false, Diags);
806 }
807 #elif defined(DRIVER_CTOR_TAKES_DEFAULTIMAGENAME)
construct_driver(const char * binary,DiagnosticsEngine & Diags)808 static Driver *construct_driver(const char *binary, DiagnosticsEngine &Diags)
809 {
810 	return new Driver(binary, llvm::sys::getDefaultTargetTriple(),
811 			    "", Diags);
812 }
813 #else
construct_driver(const char * binary,DiagnosticsEngine & Diags)814 static Driver *construct_driver(const char *binary, DiagnosticsEngine &Diags)
815 {
816 	return new Driver(binary, llvm::sys::getDefaultTargetTriple(), Diags);
817 }
818 #endif
819 
820 namespace clang { namespace driver { class Job; } }
821 
822 /* Clang changed its API from 3.5 to 3.6 and once more in 3.7.
823  * We fix this with a simple overloaded function here.
824  */
825 struct ClangAPI {
commandClangAPI826 	static Job *command(Job *J) { return J; }
commandClangAPI827 	static Job *command(Job &J) { return &J; }
commandClangAPI828 	static Command *command(Command &C) { return &C; }
829 };
830 
831 #ifdef CREATE_FROM_ARGS_TAKES_ARRAYREF
832 
833 /* Call CompilerInvocation::CreateFromArgs with the right arguments.
834  * In this case, an ArrayRef<const char *>.
835  */
create_from_args(CompilerInvocation & invocation,const ArgStringList * args,DiagnosticsEngine & Diags)836 static void create_from_args(CompilerInvocation &invocation,
837 	const ArgStringList *args, DiagnosticsEngine &Diags)
838 {
839 	CompilerInvocation::CreateFromArgs(invocation, *args, Diags);
840 }
841 
842 #else
843 
844 /* Call CompilerInvocation::CreateFromArgs with the right arguments.
845  * In this case, two "const char *" pointers.
846  */
create_from_args(CompilerInvocation & invocation,const ArgStringList * args,DiagnosticsEngine & Diags)847 static void create_from_args(CompilerInvocation &invocation,
848 	const ArgStringList *args, DiagnosticsEngine &Diags)
849 {
850 	CompilerInvocation::CreateFromArgs(invocation, args->data() + 1,
851 						args->data() + args->size(),
852 						Diags);
853 }
854 
855 #endif
856 
857 /* Create a CompilerInvocation object that stores the command line
858  * arguments constructed by the driver.
859  * The arguments are mainly useful for setting up the system include
860  * paths on newer clangs and on some platforms.
861  */
construct_invocation(const char * filename,DiagnosticsEngine & Diags)862 static CompilerInvocation *construct_invocation(const char *filename,
863 	DiagnosticsEngine &Diags)
864 {
865 	const char *binary = CLANG_PREFIX"/bin/clang";
866 	const unique_ptr<Driver> driver(construct_driver(binary, Diags));
867 	std::vector<const char *> Argv;
868 	Argv.push_back(binary);
869 	Argv.push_back(filename);
870 	const unique_ptr<Compilation> compilation(
871 		driver->BuildCompilation(llvm::ArrayRef<const char *>(Argv)));
872 	JobList &Jobs = compilation->getJobs();
873 	if (Jobs.size() < 1)
874 		return NULL;
875 
876 	Command *cmd = cast<Command>(ClangAPI::command(*Jobs.begin()));
877 	if (strcmp(cmd->getCreator().getName(), "clang"))
878 		return NULL;
879 
880 	const ArgStringList *args = &cmd->getArguments();
881 
882 	CompilerInvocation *invocation = new CompilerInvocation;
883 	create_from_args(*invocation, args, Diags);
884 	return invocation;
885 }
886 
887 #else
888 
construct_invocation(const char * filename,DiagnosticsEngine & Diags)889 static CompilerInvocation *construct_invocation(const char *filename,
890 	DiagnosticsEngine &Diags)
891 {
892 	return NULL;
893 }
894 
895 #endif
896 
897 #ifdef HAVE_BASIC_DIAGNOSTICOPTIONS_H
898 
construct_printer(CompilerInstance * Clang,int pencil)899 static MyDiagnosticPrinter *construct_printer(CompilerInstance *Clang,
900 	int pencil)
901 {
902 	return new MyDiagnosticPrinter(new DiagnosticOptions(), pencil);
903 }
904 
905 #else
906 
construct_printer(CompilerInstance * Clang,int pencil)907 static MyDiagnosticPrinter *construct_printer(CompilerInstance *Clang,
908 	int pencil)
909 {
910 	return new MyDiagnosticPrinter(Clang->getDiagnosticOpts(), pencil);
911 }
912 
913 #endif
914 
915 #ifdef CREATETARGETINFO_TAKES_SHARED_PTR
916 
create_target_info(CompilerInstance * Clang,DiagnosticsEngine & Diags)917 static TargetInfo *create_target_info(CompilerInstance *Clang,
918 	DiagnosticsEngine &Diags)
919 {
920 	shared_ptr<TargetOptions> TO = Clang->getInvocation().TargetOpts;
921 	TO->Triple = llvm::sys::getDefaultTargetTriple();
922 	return TargetInfo::CreateTargetInfo(Diags, TO);
923 }
924 
925 #elif defined(CREATETARGETINFO_TAKES_POINTER)
926 
create_target_info(CompilerInstance * Clang,DiagnosticsEngine & Diags)927 static TargetInfo *create_target_info(CompilerInstance *Clang,
928 	DiagnosticsEngine &Diags)
929 {
930 	TargetOptions &TO = Clang->getTargetOpts();
931 	TO.Triple = llvm::sys::getDefaultTargetTriple();
932 	return TargetInfo::CreateTargetInfo(Diags, &TO);
933 }
934 
935 #else
936 
create_target_info(CompilerInstance * Clang,DiagnosticsEngine & Diags)937 static TargetInfo *create_target_info(CompilerInstance *Clang,
938 	DiagnosticsEngine &Diags)
939 {
940 	TargetOptions &TO = Clang->getTargetOpts();
941 	TO.Triple = llvm::sys::getDefaultTargetTriple();
942 	return TargetInfo::CreateTargetInfo(Diags, TO);
943 }
944 
945 #endif
946 
947 #ifdef CREATEDIAGNOSTICS_TAKES_ARG
948 
create_diagnostics(CompilerInstance * Clang)949 static void create_diagnostics(CompilerInstance *Clang)
950 {
951 	Clang->createDiagnostics(0, NULL);
952 }
953 
954 #else
955 
create_diagnostics(CompilerInstance * Clang)956 static void create_diagnostics(CompilerInstance *Clang)
957 {
958 	Clang->createDiagnostics();
959 }
960 
961 #endif
962 
963 #ifdef CREATEPREPROCESSOR_TAKES_TUKIND
964 
create_preprocessor(CompilerInstance * Clang)965 static void create_preprocessor(CompilerInstance *Clang)
966 {
967 	Clang->createPreprocessor(TU_Complete);
968 }
969 
970 #else
971 
create_preprocessor(CompilerInstance * Clang)972 static void create_preprocessor(CompilerInstance *Clang)
973 {
974 	Clang->createPreprocessor();
975 }
976 
977 #endif
978 
979 #ifdef ADDPATH_TAKES_4_ARGUMENTS
980 
add_path(HeaderSearchOptions & HSO,string Path)981 void add_path(HeaderSearchOptions &HSO, string Path)
982 {
983 	HSO.AddPath(Path, frontend::Angled, false, false);
984 }
985 
986 #else
987 
add_path(HeaderSearchOptions & HSO,string Path)988 void add_path(HeaderSearchOptions &HSO, string Path)
989 {
990 	HSO.AddPath(Path, frontend::Angled, true, false, false);
991 }
992 
993 #endif
994 
995 #ifdef HAVE_SETMAINFILEID
996 
create_main_file_id(SourceManager & SM,const FileEntry * file)997 static void create_main_file_id(SourceManager &SM, const FileEntry *file)
998 {
999 	SM.setMainFileID(SM.createFileID(file, SourceLocation(),
1000 					SrcMgr::C_User));
1001 }
1002 
1003 #else
1004 
create_main_file_id(SourceManager & SM,const FileEntry * file)1005 static void create_main_file_id(SourceManager &SM, const FileEntry *file)
1006 {
1007 	SM.createMainFileID(file);
1008 }
1009 
1010 #endif
1011 
1012 #ifdef SETLANGDEFAULTS_TAKES_5_ARGUMENTS
1013 
1014 #include "set_lang_defaults_arg4.h"
1015 
set_lang_defaults(CompilerInstance * Clang)1016 static void set_lang_defaults(CompilerInstance *Clang)
1017 {
1018 	PreprocessorOptions &PO = Clang->getPreprocessorOpts();
1019 	TargetOptions &TO = Clang->getTargetOpts();
1020 	llvm::Triple T(TO.Triple);
1021 	CompilerInvocation::setLangDefaults(Clang->getLangOpts(), IK_C, T,
1022 					    setLangDefaultsArg4(PO),
1023 					    LangStandard::lang_unspecified);
1024 }
1025 
1026 #else
1027 
set_lang_defaults(CompilerInstance * Clang)1028 static void set_lang_defaults(CompilerInstance *Clang)
1029 {
1030 	CompilerInvocation::setLangDefaults(Clang->getLangOpts(), IK_C,
1031 					    LangStandard::lang_unspecified);
1032 }
1033 
1034 #endif
1035 
1036 #ifdef SETINVOCATION_TAKES_SHARED_PTR
1037 
set_invocation(CompilerInstance * Clang,CompilerInvocation * invocation)1038 static void set_invocation(CompilerInstance *Clang,
1039 	CompilerInvocation *invocation)
1040 {
1041 	Clang->setInvocation(std::shared_ptr<CompilerInvocation>(invocation));
1042 }
1043 
1044 #else
1045 
set_invocation(CompilerInstance * Clang,CompilerInvocation * invocation)1046 static void set_invocation(CompilerInstance *Clang,
1047 	CompilerInvocation *invocation)
1048 {
1049 	Clang->setInvocation(invocation);
1050 }
1051 
1052 #endif
1053 
1054 /* Helper function for ignore_error that only gets enabled if T
1055  * (which is either const FileEntry * or llvm::ErrorOr<const FileEntry *>)
1056  * has getError method, i.e., if it is llvm::ErrorOr<const FileEntry *>.
1057  */
1058 template <class T>
ignore_error_helper(const T obj,int,int[1][sizeof (obj.getError ())])1059 static const FileEntry *ignore_error_helper(const T obj, int,
1060 	int[1][sizeof(obj.getError())])
1061 {
1062 	return *obj;
1063 }
1064 
1065 /* Helper function for ignore_error that is always enabled,
1066  * but that only gets selected if the variant above is not enabled,
1067  * i.e., if T is const FileEntry *.
1068  */
1069 template <class T>
ignore_error_helper(const T obj,long,void *)1070 static const FileEntry *ignore_error_helper(const T obj, long, void *)
1071 {
1072 	return obj;
1073 }
1074 
1075 /* Given either a const FileEntry * or a llvm::ErrorOr<const FileEntry *>,
1076  * extract out the const FileEntry *.
1077  */
1078 template <class T>
ignore_error(const T obj)1079 static const FileEntry *ignore_error(const T obj)
1080 {
1081 	return ignore_error_helper(obj, 0, NULL);
1082 }
1083 
1084 /* Return the FileEntry corresponding to the given file name
1085  * in the given compiler instances, ignoring any error.
1086  */
getFile(CompilerInstance * Clang,std::string Filename)1087 static const FileEntry *getFile(CompilerInstance *Clang, std::string Filename)
1088 {
1089 	return ignore_error(Clang->getFileManager().getFile(Filename));
1090 }
1091 
1092 /* Add pet specific predefines to the preprocessor.
1093  * Currently, these are all pencil specific, so they are only
1094  * added if "pencil" is set.
1095  *
1096  * We mimic the way <command line> is handled inside clang.
1097  */
add_predefines(Preprocessor & PP,int pencil)1098 void add_predefines(Preprocessor &PP, int pencil)
1099 {
1100 	string s;
1101 
1102 	if (!pencil)
1103 		return;
1104 
1105 	s = PP.getPredefines();
1106 	s += "# 1 \"<pet>\" 1\n"
1107 	     "void __pencil_assume(int assumption);\n"
1108 	     "#define pencil_access(f) annotate(\"pencil_access(\" #f \")\")\n"
1109 	     "# 1 \"<built-in>\" 2\n";
1110 	PP.setPredefines(s);
1111 }
1112 
1113 /* Extract a pet_scop from each function in the C source file called "filename".
1114  * Each detected scop is passed to "fn".
1115  * If "function" is not NULL, only extract a pet_scop from the function
1116  * with that name.
1117  * If "autodetect" is set, extract any pet_scop we can find.
1118  * Otherwise, extract the pet_scop from the region delimited
1119  * by "scop" and "endscop" pragmas.
1120  *
1121  * We first set up the clang parser and then try to extract the
1122  * pet_scop from the appropriate function(s) in PetASTConsumer.
1123  */
foreach_scop_in_C_source(isl_ctx * ctx,const char * filename,const char * function,pet_options * options,isl_stat (* fn)(struct pet_scop * scop,void * user),void * user)1124 static isl_stat foreach_scop_in_C_source(isl_ctx *ctx,
1125 	const char *filename, const char *function, pet_options *options,
1126 	isl_stat (*fn)(struct pet_scop *scop, void *user), void *user)
1127 {
1128 	CompilerInstance *Clang = new CompilerInstance();
1129 	create_diagnostics(Clang);
1130 	DiagnosticsEngine &Diags = Clang->getDiagnostics();
1131 	Diags.setSuppressSystemWarnings(true);
1132 	TargetInfo *target = create_target_info(Clang, Diags);
1133 	Clang->setTarget(target);
1134 	set_lang_defaults(Clang);
1135 	CompilerInvocation *invocation = construct_invocation(filename, Diags);
1136 	if (invocation)
1137 		set_invocation(Clang, invocation);
1138 	Diags.setClient(construct_printer(Clang, options->pencil));
1139 	Clang->createFileManager();
1140 	Clang->createSourceManager(Clang->getFileManager());
1141 	HeaderSearchOptions &HSO = Clang->getHeaderSearchOpts();
1142 	HSO.ResourceDir = ResourceDir;
1143 	for (int i = 0; i < options->n_path; ++i)
1144 		add_path(HSO, options->paths[i]);
1145 	PreprocessorOptions &PO = Clang->getPreprocessorOpts();
1146 	for (int i = 0; i < options->n_define; ++i)
1147 		PO.addMacroDef(options->defines[i]);
1148 	create_preprocessor(Clang);
1149 	Preprocessor &PP = Clang->getPreprocessor();
1150 	add_predefines(PP, options->pencil);
1151 	PP.getBuiltinInfo().initializeBuiltins(PP.getIdentifierTable(),
1152 		PP.getLangOpts());
1153 
1154 	ScopLocList scops;
1155 
1156 	const FileEntry *file = getFile(Clang, filename);
1157 	if (!file)
1158 		isl_die(ctx, isl_error_unknown, "unable to open file",
1159 			do { delete Clang; return isl_stat_error; } while (0));
1160 	create_main_file_id(Clang->getSourceManager(), file);
1161 
1162 	Clang->createASTContext();
1163 	PetASTConsumer consumer(ctx, PP, Clang->getASTContext(), Diags,
1164 				scops, function, options, fn, user);
1165 	Sema *sema = new Sema(PP, Clang->getASTContext(), consumer);
1166 
1167 	if (!options->autodetect) {
1168 		PP.AddPragmaHandler(new PragmaScopHandler(scops));
1169 		PP.AddPragmaHandler(new PragmaEndScopHandler(scops));
1170 		PP.AddPragmaHandler(new PragmaLiveOutHandler(*sema,
1171 							consumer.live_out));
1172 	}
1173 
1174 	consumer.add_pragma_handlers(sema);
1175 
1176 	Diags.getClient()->BeginSourceFile(Clang->getLangOpts(), &PP);
1177 	ParseAST(*sema);
1178 	Diags.getClient()->EndSourceFile();
1179 
1180 	delete sema;
1181 	delete Clang;
1182 
1183 	return consumer.error ? isl_stat_error : isl_stat_ok;
1184 }
1185 
1186 /* Extract a pet_scop from each function in the C source file called "filename".
1187  * Each detected scop is passed to "fn".
1188  *
1189  * This wrapper around foreach_scop_in_C_source is mainly used to ensure
1190  * that all objects on the stack (of that function) are destroyed before we
1191  * call llvm_shutdown.
1192  */
pet_foreach_scop_in_C_source(isl_ctx * ctx,const char * filename,const char * function,isl_stat (* fn)(struct pet_scop * scop,void * user),void * user)1193 static isl_stat pet_foreach_scop_in_C_source(isl_ctx *ctx,
1194 	const char *filename, const char *function,
1195 	isl_stat (*fn)(struct pet_scop *scop, void *user), void *user)
1196 {
1197 	isl_stat r;
1198 	pet_options *options;
1199 	bool allocated = false;
1200 
1201 	options = isl_ctx_peek_pet_options(ctx);
1202 	if (!options) {
1203 		options = pet_options_new_with_defaults();
1204 		allocated = true;
1205 	}
1206 
1207 	r = foreach_scop_in_C_source(ctx, filename, function, options,
1208 					fn, user);
1209 	llvm::llvm_shutdown();
1210 
1211 	if (allocated)
1212 		pet_options_free(options);
1213 
1214 	return r;
1215 }
1216 
1217 /* Store "scop" into the address pointed to by "user".
1218  * Return -1 to indicate that we are not interested in any further scops.
1219  * This function should therefore not be called a second call
1220  * so in principle there is no need to check if we have already set *user.
1221  */
set_first_scop(pet_scop * scop,void * user)1222 static isl_stat set_first_scop(pet_scop *scop, void *user)
1223 {
1224 	pet_scop **p = (pet_scop **) user;
1225 
1226 	if (!*p)
1227 		*p = scop;
1228 	else
1229 		pet_scop_free(scop);
1230 
1231 	return isl_stat_error;
1232 }
1233 
1234 /* Extract a pet_scop from the C source file called "filename".
1235  * If "function" is not NULL, extract the pet_scop from the function
1236  * with that name.
1237  *
1238  * We start extracting scops from every function and then abort
1239  * as soon as we have extracted one scop.
1240  */
pet_scop_extract_from_C_source(isl_ctx * ctx,const char * filename,const char * function)1241 struct pet_scop *pet_scop_extract_from_C_source(isl_ctx *ctx,
1242 	const char *filename, const char *function)
1243 {
1244 	pet_scop *scop = NULL;
1245 
1246 	pet_foreach_scop_in_C_source(ctx, filename, function,
1247 					&set_first_scop, &scop);
1248 
1249 	return scop;
1250 }
1251 
1252 /* Internal data structure for pet_transform_C_source
1253  *
1254  * transform is the function that should be called to print a scop
1255  * in is the input source file
1256  * out is the output source file
1257  * end is the offset of the end of the previous scop (zero if we have not
1258  *	found any scop yet)
1259  * p is a printer that prints to out.
1260  */
1261 struct pet_transform_data {
1262 	__isl_give isl_printer *(*transform)(__isl_take isl_printer *p,
1263 		struct pet_scop *scop, void *user);
1264 	void *user;
1265 
1266 	FILE *in;
1267 	FILE *out;
1268 	unsigned end;
1269 	isl_printer *p;
1270 };
1271 
1272 /* This function is called each time a scop is detected.
1273  *
1274  * We first copy the input text code from the end of the previous scop
1275  * until the start of "scop" and then print the scop itself through
1276  * a call to data->transform.  We set up the printer to print
1277  * the transformed code with the same (initial) indentation as
1278  * the original code.
1279  * Finally, we keep track of the end of "scop" so that we can
1280  * continue copying when we find the next scop.
1281  *
1282  * Before calling data->transform, we store a pointer to the original
1283  * input file in the extended scop in case the user wants to call
1284  * pet_scop_print_original from the callback.
1285  */
pet_transform(struct pet_scop * scop,void * user)1286 static isl_stat pet_transform(struct pet_scop *scop, void *user)
1287 {
1288 	struct pet_transform_data *data = (struct pet_transform_data *) user;
1289 	unsigned start;
1290 
1291 	if (!scop)
1292 		return isl_stat_error;
1293 	start = pet_loc_get_start(scop->loc);
1294 	if (copy(data->in, data->out, data->end, start) < 0)
1295 		goto error;
1296 	data->end = pet_loc_get_end(scop->loc);
1297 	scop = pet_scop_set_input_file(scop, data->in);
1298 	data->p = isl_printer_set_indent_prefix(data->p,
1299 					pet_loc_get_indent(scop->loc));
1300 	data->p = data->transform(data->p, scop, data->user);
1301 	if (!data->p)
1302 		return isl_stat_error;
1303 	return isl_stat_ok;
1304 error:
1305 	pet_scop_free(scop);
1306 	return isl_stat_error;
1307 }
1308 
1309 /* Transform the C source file "input" by rewriting each scop
1310  * through a call to "transform".
1311  * When autodetecting scops, at most one scop per function is rewritten.
1312  * The transformed C code is written to "output".
1313  *
1314  * For each scop we find, we first copy the input text code
1315  * from the end of the previous scop (or the beginning of the file
1316  * in case of the first scop) until the start of the scop
1317  * and then print the scop itself through a call to "transform".
1318  * At the end we copy everything from the end of the final scop
1319  * until the end of the input file to "output".
1320  */
pet_transform_C_source(isl_ctx * ctx,const char * input,FILE * out,__isl_give isl_printer * (* transform)(__isl_take isl_printer * p,struct pet_scop * scop,void * user),void * user)1321 int pet_transform_C_source(isl_ctx *ctx, const char *input, FILE *out,
1322 	__isl_give isl_printer *(*transform)(__isl_take isl_printer *p,
1323 		struct pet_scop *scop, void *user), void *user)
1324 {
1325 	struct pet_transform_data data;
1326 	int r;
1327 
1328 	data.in = stdin;
1329 	data.out = out;
1330 	if (input && strcmp(input, "-")) {
1331 		data.in = fopen(input, "r");
1332 		if (!data.in)
1333 			isl_die(ctx, isl_error_unknown, "unable to open file",
1334 				return -1);
1335 	}
1336 
1337 	data.p = isl_printer_to_file(ctx, data.out);
1338 	data.p = isl_printer_set_output_format(data.p, ISL_FORMAT_C);
1339 
1340 	data.transform = transform;
1341 	data.user = user;
1342 	data.end = 0;
1343 	r = pet_foreach_scop_in_C_source(ctx, input, NULL,
1344 					&pet_transform, &data);
1345 
1346 	isl_printer_free(data.p);
1347 	if (!data.p)
1348 		r = -1;
1349 	if (r == 0 && copy(data.in, data.out, data.end, -1) < 0)
1350 		r = -1;
1351 
1352 	if (data.in != stdin)
1353 		fclose(data.in);
1354 
1355 	return r;
1356 }
1357