1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
|
//===-- JSONExporter.cpp - Export Scops as JSON -------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
//
// Export the Scops build by ScopInfo pass as a JSON file.
//
//===----------------------------------------------------------------------===//
#include "polly/JSONExporter.h"
#include "polly/DependenceInfo.h"
#include "polly/LinkAllPasses.h"
#include "polly/Options.h"
#include "polly/ScopInfo.h"
#include "polly/ScopPass.h"
#include "polly/Support/ISLTools.h"
#include "polly/Support/ScopLocation.h"
#include "llvm/ADT/Statistic.h"
#include "llvm/IR/Module.h"
#include "llvm/Support/FileSystem.h"
#include "llvm/Support/JSON.h"
#include "llvm/Support/MemoryBuffer.h"
#include "llvm/Support/ToolOutputFile.h"
#include "llvm/Support/raw_ostream.h"
#include "isl/map.h"
#include "isl/set.h"
#include <memory>
#include <string>
#include <system_error>
using namespace llvm;
using namespace polly;
#define DEBUG_TYPE "polly-import-jscop"
STATISTIC(NewAccessMapFound, "Number of updated access functions");
namespace {
static cl::opt<std::string>
ImportDir("polly-import-jscop-dir",
cl::desc("The directory to import the .jscop files from."),
cl::Hidden, cl::value_desc("Directory path"), cl::ValueRequired,
cl::init("."), cl::cat(PollyCategory));
static cl::opt<std::string>
ImportPostfix("polly-import-jscop-postfix",
cl::desc("Postfix to append to the import .jsop files."),
cl::Hidden, cl::value_desc("File postfix"), cl::ValueRequired,
cl::init(""), cl::cat(PollyCategory));
class JSONExporter : public ScopPass {
public:
static char ID;
explicit JSONExporter() : ScopPass(ID) {}
/// Export the SCoP @p S to a JSON file.
bool runOnScop(Scop &S) override;
/// Print the SCoP @p S as it is exported.
void printScop(raw_ostream &OS, Scop &S) const override;
/// Register all analyses and transformation required.
void getAnalysisUsage(AnalysisUsage &AU) const override;
};
class JSONImporter : public ScopPass {
public:
static char ID;
std::vector<std::string> NewAccessStrings;
explicit JSONImporter() : ScopPass(ID) {}
/// Import new access functions for SCoP @p S from a JSON file.
bool runOnScop(Scop &S) override;
/// Print the SCoP @p S and the imported access functions.
void printScop(raw_ostream &OS, Scop &S) const override;
/// Register all analyses and transformation required.
void getAnalysisUsage(AnalysisUsage &AU) const override;
};
} // namespace
static std::string getFileName(Scop &S, StringRef Suffix = "") {
std::string FunctionName = S.getFunction().getName().str();
std::string FileName = FunctionName + "___" + S.getNameStr() + ".jscop";
if (Suffix != "")
FileName += "." + Suffix.str();
return FileName;
}
/// Export all arrays from the Scop.
///
/// @param S The Scop containing the arrays.
///
/// @returns Json::Value containing the arrays.
static json::Array exportArrays(const Scop &S) {
json::Array Arrays;
std::string Buffer;
llvm::raw_string_ostream RawStringOstream(Buffer);
for (auto &SAI : S.arrays()) {
if (!SAI->isArrayKind())
continue;
json::Object Array;
json::Array Sizes;
Array["name"] = SAI->getName();
unsigned i = 0;
if (!SAI->getDimensionSize(i)) {
Sizes.push_back("*");
i++;
}
for (; i < SAI->getNumberOfDimensions(); i++) {
SAI->getDimensionSize(i)->print(RawStringOstream);
Sizes.push_back(RawStringOstream.str());
Buffer.clear();
}
Array["sizes"] = std::move(Sizes);
SAI->getElementType()->print(RawStringOstream);
Array["type"] = RawStringOstream.str();
Buffer.clear();
Arrays.push_back(std::move(Array));
}
return Arrays;
}
static json::Value getJSON(Scop &S) {
json::Object root;
unsigned LineBegin, LineEnd;
std::string FileName;
getDebugLocation(&S.getRegion(), LineBegin, LineEnd, FileName);
std::string Location;
if (LineBegin != (unsigned)-1)
Location = FileName + ":" + std::to_string(LineBegin) + "-" +
std::to_string(LineEnd);
root["name"] = S.getNameStr();
root["context"] = S.getContextStr();
if (LineBegin != (unsigned)-1)
root["location"] = Location;
root["arrays"] = exportArrays(S);
root["statements"];
json::Array Statements;
for (ScopStmt &Stmt : S) {
json::Object statement;
statement["name"] = Stmt.getBaseName();
statement["domain"] = Stmt.getDomainStr();
statement["schedule"] = Stmt.getScheduleStr();
json::Array Accesses;
for (MemoryAccess *MA : Stmt) {
json::Object access;
access["kind"] = MA->isRead() ? "read" : "write";
access["relation"] = MA->getAccessRelationStr();
Accesses.push_back(std::move(access));
}
statement["accesses"] = std::move(Accesses);
Statements.push_back(std::move(statement));
}
root["statements"] = std::move(Statements);
return json::Value(std::move(root));
}
static void exportScop(Scop &S) {
std::string FileName = ImportDir + "/" + getFileName(S);
json::Value jscop = getJSON(S);
// Write to file.
std::error_code EC;
ToolOutputFile F(FileName, EC, llvm::sys::fs::OF_TextWithCRLF);
std::string FunctionName = S.getFunction().getName().str();
errs() << "Writing JScop '" << S.getNameStr() << "' in function '"
<< FunctionName << "' to '" << FileName << "'.\n";
if (!EC) {
F.os() << formatv("{0:3}", jscop);
F.os().close();
if (!F.os().has_error()) {
errs() << "\n";
F.keep();
return;
}
}
errs() << " error opening file for writing!\n";
F.os().clear_error();
}
typedef Dependences::StatementToIslMapTy StatementToIslMapTy;
/// Import a new context from JScop.
///
/// @param S The scop to update.
/// @param JScop The JScop file describing the new schedule.
///
/// @returns True if the import succeeded, otherwise False.
static bool importContext(Scop &S, const json::Object &JScop) {
isl::set OldContext = S.getContext();
// Check if key 'context' is present.
if (!JScop.get("context")) {
errs() << "JScop file has no key named 'context'.\n";
return false;
}
isl::set NewContext =
isl::set{S.getIslCtx().get(), JScop.getString("context").value().str()};
// Check whether the context was parsed successfully.
if (NewContext.is_null()) {
errs() << "The context was not parsed successfully by ISL.\n";
return false;
}
// Check if the isl_set is a parameter set.
if (!NewContext.is_params()) {
errs() << "The isl_set is not a parameter set.\n";
return false;
}
unsigned OldContextDim = unsignedFromIslSize(OldContext.dim(isl::dim::param));
unsigned NewContextDim = unsignedFromIslSize(NewContext.dim(isl::dim::param));
// Check if the imported context has the right number of parameters.
if (OldContextDim != NewContextDim) {
errs() << "Imported context has the wrong number of parameters : "
<< "Found " << NewContextDim << " Expected " << OldContextDim
<< "\n";
return false;
}
for (unsigned i = 0; i < OldContextDim; i++) {
isl::id Id = OldContext.get_dim_id(isl::dim::param, i);
NewContext = NewContext.set_dim_id(isl::dim::param, i, Id);
}
S.setContext(NewContext);
return true;
}
/// Import a new schedule from JScop.
///
/// ... and verify that the new schedule does preserve existing data
/// dependences.
///
/// @param S The scop to update.
/// @param JScop The JScop file describing the new schedule.
/// @param D The data dependences of the @p S.
///
/// @returns True if the import succeeded, otherwise False.
static bool importSchedule(Scop &S, const json::Object &JScop,
const Dependences &D) {
StatementToIslMapTy NewSchedule;
// Check if key 'statements' is present.
if (!JScop.get("statements")) {
errs() << "JScop file has no key name 'statements'.\n";
return false;
}
const json::Array &statements = *JScop.getArray("statements");
// Check whether the number of indices equals the number of statements
if (statements.size() != S.getSize()) {
errs() << "The number of indices and the number of statements differ.\n";
return false;
}
int Index = 0;
for (ScopStmt &Stmt : S) {
// Check if key 'schedule' is present.
if (!statements[Index].getAsObject()->get("schedule")) {
errs() << "Statement " << Index << " has no 'schedule' key.\n";
return false;
}
std::optional<StringRef> Schedule =
statements[Index].getAsObject()->getString("schedule");
assert(Schedule.has_value() &&
"Schedules that contain extension nodes require special handling.");
isl_map *Map = isl_map_read_from_str(S.getIslCtx().get(),
Schedule.value().str().c_str());
// Check whether the schedule was parsed successfully
if (!Map) {
errs() << "The schedule was not parsed successfully (index = " << Index
<< ").\n";
return false;
}
isl_space *Space = Stmt.getDomainSpace().release();
// Copy the old tuple id. This is necessary to retain the user pointer,
// that stores the reference to the ScopStmt this schedule belongs to.
Map = isl_map_set_tuple_id(Map, isl_dim_in,
isl_space_get_tuple_id(Space, isl_dim_set));
for (isl_size i = 0; i < isl_space_dim(Space, isl_dim_param); i++) {
isl_id *Id = isl_space_get_dim_id(Space, isl_dim_param, i);
Map = isl_map_set_dim_id(Map, isl_dim_param, i, Id);
}
isl_space_free(Space);
NewSchedule[&Stmt] = isl::manage(Map);
Index++;
}
// Check whether the new schedule is valid or not.
if (!D.isValidSchedule(S, NewSchedule)) {
errs() << "JScop file contains a schedule that changes the "
<< "dependences. Use -disable-polly-legality to continue anyways\n";
return false;
}
auto ScheduleMap = isl::union_map::empty(S.getIslCtx());
for (ScopStmt &Stmt : S) {
if (NewSchedule.find(&Stmt) != NewSchedule.end())
ScheduleMap = ScheduleMap.unite(NewSchedule[&Stmt]);
else
ScheduleMap = ScheduleMap.unite(Stmt.getSchedule());
}
S.setSchedule(ScheduleMap);
return true;
}
/// Import new memory accesses from JScop.
///
/// @param S The scop to update.
/// @param JScop The JScop file describing the new schedule.
/// @param DL The data layout to assume.
/// @param NewAccessStrings optionally record the imported access strings
///
/// @returns True if the import succeeded, otherwise False.
static bool
importAccesses(Scop &S, const json::Object &JScop, const DataLayout &DL,
std::vector<std::string> *NewAccessStrings = nullptr) {
int StatementIdx = 0;
// Check if key 'statements' is present.
if (!JScop.get("statements")) {
errs() << "JScop file has no key name 'statements'.\n";
return false;
}
const json::Array &statements = *JScop.getArray("statements");
// Check whether the number of indices equals the number of statements
if (statements.size() != S.getSize()) {
errs() << "The number of indices and the number of statements differ.\n";
return false;
}
for (ScopStmt &Stmt : S) {
int MemoryAccessIdx = 0;
const json::Object *Statement = statements[StatementIdx].getAsObject();
assert(Statement);
// Check if key 'accesses' is present.
if (!Statement->get("accesses")) {
errs()
<< "Statement from JScop file has no key name 'accesses' for index "
<< StatementIdx << ".\n";
return false;
}
const json::Array &JsonAccesses = *Statement->getArray("accesses");
// Check whether the number of indices equals the number of memory
// accesses
if (Stmt.size() != JsonAccesses.size()) {
errs() << "The number of memory accesses in the JSop file and the number "
"of memory accesses differ for index "
<< StatementIdx << ".\n";
return false;
}
for (MemoryAccess *MA : Stmt) {
// Check if key 'relation' is present.
const json::Object *JsonMemoryAccess =
JsonAccesses[MemoryAccessIdx].getAsObject();
assert(JsonMemoryAccess);
if (!JsonMemoryAccess->get("relation")) {
errs() << "Memory access number " << MemoryAccessIdx
<< " has no key name 'relation' for statement number "
<< StatementIdx << ".\n";
return false;
}
StringRef Accesses = *JsonMemoryAccess->getString("relation");
isl_map *NewAccessMap =
isl_map_read_from_str(S.getIslCtx().get(), Accesses.str().c_str());
// Check whether the access was parsed successfully
if (!NewAccessMap) {
errs() << "The access was not parsed successfully by ISL.\n";
return false;
}
isl_map *CurrentAccessMap = MA->getAccessRelation().release();
// Check if the number of parameter change
if (isl_map_dim(NewAccessMap, isl_dim_param) !=
isl_map_dim(CurrentAccessMap, isl_dim_param)) {
errs() << "JScop file changes the number of parameter dimensions.\n";
isl_map_free(CurrentAccessMap);
isl_map_free(NewAccessMap);
return false;
}
isl_id *NewOutId;
// If the NewAccessMap has zero dimensions, it is the scalar access; it
// must be the same as before.
// If it has at least one dimension, it's an array access; search for
// its ScopArrayInfo.
if (isl_map_dim(NewAccessMap, isl_dim_out) >= 1) {
NewOutId = isl_map_get_tuple_id(NewAccessMap, isl_dim_out);
auto *SAI = S.getArrayInfoByName(isl_id_get_name(NewOutId));
isl_id *OutId = isl_map_get_tuple_id(CurrentAccessMap, isl_dim_out);
auto *OutSAI = ScopArrayInfo::getFromId(isl::manage(OutId));
if (!SAI || SAI->getElementType() != OutSAI->getElementType()) {
errs() << "JScop file contains access function with undeclared "
"ScopArrayInfo\n";
isl_map_free(CurrentAccessMap);
isl_map_free(NewAccessMap);
isl_id_free(NewOutId);
return false;
}
isl_id_free(NewOutId);
NewOutId = SAI->getBasePtrId().release();
} else {
NewOutId = isl_map_get_tuple_id(CurrentAccessMap, isl_dim_out);
}
NewAccessMap = isl_map_set_tuple_id(NewAccessMap, isl_dim_out, NewOutId);
if (MA->isArrayKind()) {
// We keep the old alignment, thus we cannot allow accesses to memory
// locations that were not accessed before if the alignment of the
// access is not the default alignment.
bool SpecialAlignment = true;
if (LoadInst *LoadI = dyn_cast<LoadInst>(MA->getAccessInstruction())) {
SpecialAlignment =
DL.getABITypeAlign(LoadI->getType()) != LoadI->getAlign();
} else if (StoreInst *StoreI =
dyn_cast<StoreInst>(MA->getAccessInstruction())) {
SpecialAlignment =
DL.getABITypeAlign(StoreI->getValueOperand()->getType()) !=
StoreI->getAlign();
}
if (SpecialAlignment) {
isl_set *NewAccessSet = isl_map_range(isl_map_copy(NewAccessMap));
isl_set *CurrentAccessSet =
isl_map_range(isl_map_copy(CurrentAccessMap));
bool IsSubset = isl_set_is_subset(NewAccessSet, CurrentAccessSet);
isl_set_free(NewAccessSet);
isl_set_free(CurrentAccessSet);
// Check if the JScop file changes the accessed memory.
if (!IsSubset) {
errs() << "JScop file changes the accessed memory\n";
isl_map_free(CurrentAccessMap);
isl_map_free(NewAccessMap);
return false;
}
}
}
// We need to copy the isl_ids for the parameter dimensions to the new
// map. Without doing this the current map would have different
// ids then the new one, even though both are named identically.
for (isl_size i = 0; i < isl_map_dim(CurrentAccessMap, isl_dim_param);
i++) {
isl_id *Id = isl_map_get_dim_id(CurrentAccessMap, isl_dim_param, i);
NewAccessMap = isl_map_set_dim_id(NewAccessMap, isl_dim_param, i, Id);
}
// Copy the old tuple id. This is necessary to retain the user pointer,
// that stores the reference to the ScopStmt this access belongs to.
isl_id *Id = isl_map_get_tuple_id(CurrentAccessMap, isl_dim_in);
NewAccessMap = isl_map_set_tuple_id(NewAccessMap, isl_dim_in, Id);
auto NewAccessDomain = isl_map_domain(isl_map_copy(NewAccessMap));
auto CurrentAccessDomain = isl_map_domain(isl_map_copy(CurrentAccessMap));
if (!isl_set_has_equal_space(NewAccessDomain, CurrentAccessDomain)) {
errs() << "JScop file contains access function with incompatible "
<< "dimensions\n";
isl_map_free(CurrentAccessMap);
isl_map_free(NewAccessMap);
isl_set_free(NewAccessDomain);
isl_set_free(CurrentAccessDomain);
return false;
}
NewAccessDomain =
isl_set_intersect_params(NewAccessDomain, S.getContext().release());
CurrentAccessDomain = isl_set_intersect_params(CurrentAccessDomain,
S.getContext().release());
CurrentAccessDomain =
isl_set_intersect(CurrentAccessDomain, Stmt.getDomain().release());
if (MA->isRead() &&
isl_set_is_subset(CurrentAccessDomain, NewAccessDomain) ==
isl_bool_false) {
errs() << "Mapping not defined for all iteration domain elements\n";
isl_set_free(CurrentAccessDomain);
isl_set_free(NewAccessDomain);
isl_map_free(CurrentAccessMap);
isl_map_free(NewAccessMap);
return false;
}
isl_set_free(CurrentAccessDomain);
isl_set_free(NewAccessDomain);
if (!isl_map_is_equal(NewAccessMap, CurrentAccessMap)) {
// Statistics.
++NewAccessMapFound;
if (NewAccessStrings)
NewAccessStrings->push_back(Accesses.str());
MA->setNewAccessRelation(isl::manage(NewAccessMap));
} else {
isl_map_free(NewAccessMap);
}
isl_map_free(CurrentAccessMap);
MemoryAccessIdx++;
}
StatementIdx++;
}
return true;
}
/// Check whether @p SAI and @p Array represent the same array.
static bool areArraysEqual(ScopArrayInfo *SAI, const json::Object &Array) {
std::string Buffer;
llvm::raw_string_ostream RawStringOstream(Buffer);
// Check if key 'type' is present.
if (!Array.get("type")) {
errs() << "Array has no key 'type'.\n";
return false;
}
// Check if key 'sizes' is present.
if (!Array.get("sizes")) {
errs() << "Array has no key 'sizes'.\n";
return false;
}
// Check if key 'name' is present.
if (!Array.get("name")) {
errs() << "Array has no key 'name'.\n";
return false;
}
if (SAI->getName() != *Array.getString("name"))
return false;
if (SAI->getNumberOfDimensions() != Array.getArray("sizes")->size())
return false;
for (unsigned i = 1; i < Array.getArray("sizes")->size(); i++) {
SAI->getDimensionSize(i)->print(RawStringOstream);
const json::Array &SizesArray = *Array.getArray("sizes");
if (RawStringOstream.str() != SizesArray[i].getAsString().value())
return false;
Buffer.clear();
}
// Check if key 'type' differs from the current one or is not valid.
SAI->getElementType()->print(RawStringOstream);
if (RawStringOstream.str() != Array.getString("type").value()) {
errs() << "Array has not a valid type.\n";
return false;
}
return true;
}
/// Get the accepted primitive type from its textual representation
/// @p TypeTextRepresentation.
///
/// @param TypeTextRepresentation The textual representation of the type.
/// @return The pointer to the primitive type, if this type is accepted
/// or nullptr otherwise.
static Type *parseTextType(const std::string &TypeTextRepresentation,
LLVMContext &LLVMContext) {
std::map<std::string, Type *> MapStrToType = {
{"void", Type::getVoidTy(LLVMContext)},
{"half", Type::getHalfTy(LLVMContext)},
{"float", Type::getFloatTy(LLVMContext)},
{"double", Type::getDoubleTy(LLVMContext)},
{"x86_fp80", Type::getX86_FP80Ty(LLVMContext)},
{"fp128", Type::getFP128Ty(LLVMContext)},
{"ppc_fp128", Type::getPPC_FP128Ty(LLVMContext)},
{"i1", Type::getInt1Ty(LLVMContext)},
{"i8", Type::getInt8Ty(LLVMContext)},
{"i16", Type::getInt16Ty(LLVMContext)},
{"i32", Type::getInt32Ty(LLVMContext)},
{"i64", Type::getInt64Ty(LLVMContext)},
{"i128", Type::getInt128Ty(LLVMContext)}};
auto It = MapStrToType.find(TypeTextRepresentation);
if (It != MapStrToType.end())
return It->second;
errs() << "Textual representation can not be parsed: "
<< TypeTextRepresentation << "\n";
return nullptr;
}
/// Import new arrays from JScop.
///
/// @param S The scop to update.
/// @param JScop The JScop file describing new arrays.
///
/// @returns True if the import succeeded, otherwise False.
static bool importArrays(Scop &S, const json::Object &JScop) {
if (!JScop.get("arrays"))
return true;
const json::Array &Arrays = *JScop.getArray("arrays");
if (Arrays.size() == 0)
return true;
unsigned ArrayIdx = 0;
for (auto &SAI : S.arrays()) {
if (!SAI->isArrayKind())
continue;
if (ArrayIdx + 1 > Arrays.size()) {
errs() << "Not enough array entries in JScop file.\n";
return false;
}
if (!areArraysEqual(SAI, *Arrays[ArrayIdx].getAsObject())) {
errs() << "No match for array '" << SAI->getName() << "' in JScop.\n";
return false;
}
ArrayIdx++;
}
for (; ArrayIdx < Arrays.size(); ArrayIdx++) {
const json::Object &Array = *Arrays[ArrayIdx].getAsObject();
auto *ElementType =
parseTextType(Array.get("type")->getAsString().value().str(),
S.getSE()->getContext());
if (!ElementType) {
errs() << "Error while parsing element type for new array.\n";
return false;
}
const json::Array &SizesArray = *Array.getArray("sizes");
std::vector<unsigned> DimSizes;
for (unsigned i = 0; i < SizesArray.size(); i++) {
auto Size = std::stoi(SizesArray[i].getAsString()->str());
// Check if the size if positive.
if (Size <= 0) {
errs() << "The size at index " << i << " is =< 0.\n";
return false;
}
DimSizes.push_back(Size);
}
auto NewSAI = S.createScopArrayInfo(
ElementType, Array.getString("name").value().str(), DimSizes);
if (Array.get("allocation")) {
NewSAI->setIsOnHeap(Array.getString("allocation").value() == "heap");
}
}
return true;
}
/// Import a Scop from a JSCOP file
/// @param S The scop to be modified
/// @param D Dependence Info
/// @param DL The DataLayout of the function
/// @param NewAccessStrings Optionally record the imported access strings
///
/// @returns true on success, false otherwise. Beware that if this returns
/// false, the Scop may still have been modified. In this case the Scop contains
/// invalid information.
static bool importScop(Scop &S, const Dependences &D, const DataLayout &DL,
std::vector<std::string> *NewAccessStrings = nullptr) {
std::string FileName = ImportDir + "/" + getFileName(S, ImportPostfix);
std::string FunctionName = S.getFunction().getName().str();
errs() << "Reading JScop '" << S.getNameStr() << "' in function '"
<< FunctionName << "' from '" << FileName << "'.\n";
ErrorOr<std::unique_ptr<MemoryBuffer>> result =
MemoryBuffer::getFile(FileName);
std::error_code ec = result.getError();
if (ec) {
errs() << "File could not be read: " << ec.message() << "\n";
return false;
}
Expected<json::Value> ParseResult =
json::parse(result.get().get()->getBuffer());
if (Error E = ParseResult.takeError()) {
errs() << "JSCoP file could not be parsed\n";
errs() << E << "\n";
consumeError(std::move(E));
return false;
}
json::Object &jscop = *ParseResult.get().getAsObject();
bool Success = importContext(S, jscop);
if (!Success)
return false;
Success = importSchedule(S, jscop, D);
if (!Success)
return false;
Success = importArrays(S, jscop);
if (!Success)
return false;
Success = importAccesses(S, jscop, DL, NewAccessStrings);
if (!Success)
return false;
return true;
}
char JSONExporter::ID = 0;
void JSONExporter::printScop(raw_ostream &OS, Scop &S) const { OS << S; }
bool JSONExporter::runOnScop(Scop &S) {
exportScop(S);
return false;
}
void JSONExporter::getAnalysisUsage(AnalysisUsage &AU) const {
AU.setPreservesAll();
AU.addRequired<ScopInfoRegionPass>();
}
Pass *polly::createJSONExporterPass() { return new JSONExporter(); }
PreservedAnalyses JSONExportPass::run(Scop &S, ScopAnalysisManager &SAM,
ScopStandardAnalysisResults &SAR,
SPMUpdater &) {
exportScop(S);
return PreservedAnalyses::all();
}
char JSONImporter::ID = 0;
void JSONImporter::printScop(raw_ostream &OS, Scop &S) const {
OS << S;
for (std::vector<std::string>::const_iterator I = NewAccessStrings.begin(),
E = NewAccessStrings.end();
I != E; I++)
OS << "New access function '" << *I << "' detected in JSCOP file\n";
}
bool JSONImporter::runOnScop(Scop &S) {
const Dependences &D =
getAnalysis<DependenceInfo>().getDependences(Dependences::AL_Statement);
const DataLayout &DL = S.getFunction().getParent()->getDataLayout();
if (!importScop(S, D, DL, &NewAccessStrings))
report_fatal_error("Tried to import a malformed jscop file.");
return false;
}
void JSONImporter::getAnalysisUsage(AnalysisUsage &AU) const {
ScopPass::getAnalysisUsage(AU);
AU.addRequired<DependenceInfo>();
// TODO: JSONImporter should throw away DependenceInfo.
AU.addPreserved<DependenceInfo>();
}
Pass *polly::createJSONImporterPass() { return new JSONImporter(); }
PreservedAnalyses JSONImportPass::run(Scop &S, ScopAnalysisManager &SAM,
ScopStandardAnalysisResults &SAR,
SPMUpdater &) {
const Dependences &D =
SAM.getResult<DependenceAnalysis>(S, SAR).getDependences(
Dependences::AL_Statement);
const DataLayout &DL = S.getFunction().getParent()->getDataLayout();
if (!importScop(S, D, DL))
report_fatal_error("Tried to import a malformed jscop file.");
// This invalidates all analyses on Scop.
PreservedAnalyses PA;
PA.preserveSet<AllAnalysesOn<Module>>();
PA.preserveSet<AllAnalysesOn<Function>>();
PA.preserveSet<AllAnalysesOn<Loop>>();
return PA;
}
INITIALIZE_PASS_BEGIN(JSONExporter, "polly-export-jscop",
"Polly - Export Scops as JSON"
" (Writes a .jscop file for each Scop)",
false, false);
INITIALIZE_PASS_DEPENDENCY(DependenceInfo)
INITIALIZE_PASS_END(JSONExporter, "polly-export-jscop",
"Polly - Export Scops as JSON"
" (Writes a .jscop file for each Scop)",
false, false)
INITIALIZE_PASS_BEGIN(JSONImporter, "polly-import-jscop",
"Polly - Import Scops from JSON"
" (Reads a .jscop file for each Scop)",
false, false);
INITIALIZE_PASS_DEPENDENCY(DependenceInfo)
INITIALIZE_PASS_END(JSONImporter, "polly-import-jscop",
"Polly - Import Scops from JSON"
" (Reads a .jscop file for each Scop)",
false, false)
//===----------------------------------------------------------------------===//
namespace {
/// Print result from JSONImporter.
class JSONImporterPrinterLegacyPass final : public ScopPass {
public:
static char ID;
JSONImporterPrinterLegacyPass() : JSONImporterPrinterLegacyPass(outs()){};
explicit JSONImporterPrinterLegacyPass(llvm::raw_ostream &OS)
: ScopPass(ID), OS(OS) {}
bool runOnScop(Scop &S) override {
JSONImporter &P = getAnalysis<JSONImporter>();
OS << "Printing analysis '" << P.getPassName() << "' for region: '"
<< S.getRegion().getNameStr() << "' in function '"
<< S.getFunction().getName() << "':\n";
P.printScop(OS, S);
return false;
}
void getAnalysisUsage(AnalysisUsage &AU) const override {
ScopPass::getAnalysisUsage(AU);
AU.addRequired<JSONImporter>();
AU.setPreservesAll();
}
private:
llvm::raw_ostream &OS;
};
char JSONImporterPrinterLegacyPass::ID = 0;
} // namespace
Pass *polly::createJSONImporterPrinterLegacyPass(llvm::raw_ostream &OS) {
return new JSONImporterPrinterLegacyPass(OS);
}
INITIALIZE_PASS_BEGIN(JSONImporterPrinterLegacyPass, "polly-print-import-jscop",
"Polly - Print Scop import result", false, false)
INITIALIZE_PASS_DEPENDENCY(JSONImporter)
INITIALIZE_PASS_END(JSONImporterPrinterLegacyPass, "polly-print-import-jscop",
"Polly - Print Scop import result", false, false)
|