1 //===-- JSONExporter.cpp  - Export Scops as JSON  -------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // Export the Scops build by ScopInfo pass as a JSON file.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "polly/LinkAllPasses.h"
15 #include "polly/Dependences.h"
16 #include "polly/Options.h"
17 #include "polly/ScopInfo.h"
18 #include "polly/ScopPass.h"
19 #include "llvm/ADT/Statistic.h"
20 #include "llvm/Support/FileSystem.h"
21 #include "llvm/Support/MemoryBuffer.h"
22 #include "llvm/Support/ToolOutputFile.h"
23 
24 #include "json/reader.h"
25 #include "json/writer.h"
26 
27 #include "isl/set.h"
28 #include "isl/map.h"
29 #include "isl/constraint.h"
30 #include "isl/printer.h"
31 
32 #include <memory>
33 #include <string>
34 #include <system_error>
35 
36 using namespace llvm;
37 using namespace polly;
38 
39 #define DEBUG_TYPE "polly-import-jscop"
40 
41 STATISTIC(NewAccessMapFound, "Number of updated access functions");
42 
43 namespace {
44 static cl::opt<std::string>
45     ImportDir("polly-import-jscop-dir",
46               cl::desc("The directory to import the .jscop files from."),
47               cl::Hidden, cl::value_desc("Directory path"), cl::ValueRequired,
48               cl::init("."), cl::cat(PollyCategory));
49 
50 static cl::opt<std::string>
51     ImportPostfix("polly-import-jscop-postfix",
52                   cl::desc("Postfix to append to the import .jsop files."),
53                   cl::Hidden, cl::value_desc("File postfix"), cl::ValueRequired,
54                   cl::init(""), cl::cat(PollyCategory));
55 
56 struct JSONExporter : public ScopPass {
57   static char ID;
58   Scop *S;
59   explicit JSONExporter() : ScopPass(ID) {}
60 
61   std::string getFileName(Scop *S) const;
62   Json::Value getJSON(Scop &scop) const;
63   virtual bool runOnScop(Scop &S);
64   void printScop(raw_ostream &OS) const;
65   void getAnalysisUsage(AnalysisUsage &AU) const;
66 };
67 
68 struct JSONImporter : public ScopPass {
69   static char ID;
70   Scop *S;
71   std::vector<std::string> newAccessStrings;
72   explicit JSONImporter() : ScopPass(ID) {}
73 
74   std::string getFileName(Scop *S) const;
75   virtual bool runOnScop(Scop &S);
76   void printScop(raw_ostream &OS) const;
77   void getAnalysisUsage(AnalysisUsage &AU) const;
78 };
79 }
80 
81 char JSONExporter::ID = 0;
82 std::string JSONExporter::getFileName(Scop *S) const {
83   std::string FunctionName = S->getRegion().getEntry()->getParent()->getName();
84   std::string FileName = FunctionName + "___" + S->getNameStr() + ".jscop";
85   return FileName;
86 }
87 
88 void JSONExporter::printScop(raw_ostream &OS) const { S->print(OS); }
89 
90 Json::Value JSONExporter::getJSON(Scop &scop) const {
91   Json::Value root;
92 
93   root["name"] = S->getRegion().getNameStr();
94   root["context"] = S->getContextStr();
95   root["statements"];
96 
97   for (Scop::iterator SI = S->begin(), SE = S->end(); SI != SE; ++SI) {
98     ScopStmt *Stmt = *SI;
99 
100     Json::Value statement;
101 
102     statement["name"] = Stmt->getBaseName();
103     statement["domain"] = Stmt->getDomainStr();
104     statement["schedule"] = Stmt->getScatteringStr();
105     statement["accesses"];
106 
107     for (MemoryAccess *MA : *Stmt) {
108       Json::Value access;
109 
110       access["kind"] = MA->isRead() ? "read" : "write";
111       access["relation"] = MA->getAccessRelationStr();
112 
113       statement["accesses"].append(access);
114     }
115 
116     root["statements"].append(statement);
117   }
118 
119   return root;
120 }
121 
122 bool JSONExporter::runOnScop(Scop &scop) {
123   S = &scop;
124   Region &R = S->getRegion();
125 
126   std::string FileName = ImportDir + "/" + getFileName(S);
127 
128   Json::Value jscop = getJSON(scop);
129   Json::StyledWriter writer;
130   std::string fileContent = writer.write(jscop);
131 
132   // Write to file.
133   std::string ErrInfo;
134   tool_output_file F(FileName.c_str(), ErrInfo, llvm::sys::fs::F_Text);
135 
136   std::string FunctionName = R.getEntry()->getParent()->getName();
137   errs() << "Writing JScop '" << R.getNameStr() << "' in function '"
138          << FunctionName << "' to '" << FileName << "'.\n";
139 
140   if (ErrInfo.empty()) {
141     F.os() << fileContent;
142     F.os().close();
143     if (!F.os().has_error()) {
144       errs() << "\n";
145       F.keep();
146       return false;
147     }
148   }
149 
150   errs() << "  error opening file for writing!\n";
151   F.os().clear_error();
152 
153   return false;
154 }
155 
156 void JSONExporter::getAnalysisUsage(AnalysisUsage &AU) const {
157   AU.setPreservesAll();
158   AU.addRequired<ScopInfo>();
159 }
160 
161 Pass *polly::createJSONExporterPass() { return new JSONExporter(); }
162 
163 char JSONImporter::ID = 0;
164 std::string JSONImporter::getFileName(Scop *S) const {
165   std::string FunctionName = S->getRegion().getEntry()->getParent()->getName();
166   std::string FileName = FunctionName + "___" + S->getNameStr() + ".jscop";
167 
168   if (ImportPostfix != "")
169     FileName += "." + ImportPostfix;
170 
171   return FileName;
172 }
173 
174 void JSONImporter::printScop(raw_ostream &OS) const {
175   S->print(OS);
176   for (std::vector<std::string>::const_iterator I = newAccessStrings.begin(),
177                                                 E = newAccessStrings.end();
178        I != E; I++)
179     OS << "New access function '" << *I << "'detected in JSCOP file\n";
180 }
181 
182 typedef Dependences::StatementToIslMapTy StatementToIslMapTy;
183 
184 bool JSONImporter::runOnScop(Scop &scop) {
185   S = &scop;
186   Region &R = S->getRegion();
187   Dependences *D = &getAnalysis<Dependences>();
188 
189   std::string FileName = ImportDir + "/" + getFileName(S);
190 
191   std::string FunctionName = R.getEntry()->getParent()->getName();
192   errs() << "Reading JScop '" << R.getNameStr() << "' in function '"
193          << FunctionName << "' from '" << FileName << "'.\n";
194   ErrorOr<std::unique_ptr<MemoryBuffer>> result =
195       MemoryBuffer::getFile(FileName);
196   std::error_code ec = result.getError();
197 
198   if (ec) {
199     errs() << "File could not be read: " << ec.message() << "\n";
200     return false;
201   }
202 
203   Json::Reader reader;
204   Json::Value jscop;
205 
206   bool parsingSuccessful = reader.parse(result.get()->getBufferStart(), jscop);
207 
208   if (!parsingSuccessful) {
209     errs() << "JSCoP file could not be parsed\n";
210     return false;
211   }
212 
213   isl_set *OldContext = S->getContext();
214   isl_set *NewContext =
215       isl_set_read_from_str(S->getIslCtx(), jscop["context"].asCString());
216 
217   for (unsigned i = 0; i < isl_set_dim(OldContext, isl_dim_param); i++) {
218     isl_id *id = isl_set_get_dim_id(OldContext, isl_dim_param, i);
219     NewContext = isl_set_set_dim_id(NewContext, isl_dim_param, i, id);
220   }
221 
222   isl_set_free(OldContext);
223   S->setContext(NewContext);
224 
225   StatementToIslMapTy &NewScattering = *(new StatementToIslMapTy());
226 
227   int index = 0;
228 
229   for (Scop::iterator SI = S->begin(), SE = S->end(); SI != SE; ++SI) {
230     Json::Value schedule = jscop["statements"][index]["schedule"];
231     isl_map *m = isl_map_read_from_str(S->getIslCtx(), schedule.asCString());
232     isl_space *Space = (*SI)->getDomainSpace();
233 
234     // Copy the old tuple id. This is necessary to retain the user pointer,
235     // that stores the reference to the ScopStmt this scattering belongs to.
236     m = isl_map_set_tuple_id(m, isl_dim_in,
237                              isl_space_get_tuple_id(Space, isl_dim_set));
238     isl_space_free(Space);
239     NewScattering[*SI] = m;
240     index++;
241   }
242 
243   if (!D->isValidScattering(&NewScattering)) {
244     errs() << "JScop file contains a scattering that changes the "
245            << "dependences. Use -disable-polly-legality to continue anyways\n";
246     for (StatementToIslMapTy::iterator SI = NewScattering.begin(),
247                                        SE = NewScattering.end();
248          SI != SE; ++SI)
249       isl_map_free(SI->second);
250     return false;
251   }
252 
253   for (Scop::iterator SI = S->begin(), SE = S->end(); SI != SE; ++SI) {
254     ScopStmt *Stmt = *SI;
255 
256     if (NewScattering.find(Stmt) != NewScattering.end())
257       Stmt->setScattering(NewScattering[Stmt]);
258   }
259 
260   int statementIdx = 0;
261   for (Scop::iterator SI = S->begin(), SE = S->end(); SI != SE; ++SI) {
262     ScopStmt *Stmt = *SI;
263 
264     int memoryAccessIdx = 0;
265     for (MemoryAccess *MA : *Stmt) {
266       Json::Value accesses = jscop["statements"][statementIdx]["accesses"]
267                                   [memoryAccessIdx]["relation"];
268       isl_map *newAccessMap =
269           isl_map_read_from_str(S->getIslCtx(), accesses.asCString());
270       isl_map *currentAccessMap = MA->getAccessRelation();
271 
272       if (isl_map_dim(newAccessMap, isl_dim_param) !=
273           isl_map_dim(currentAccessMap, isl_dim_param)) {
274         errs() << "JScop file changes the number of parameter dimensions\n";
275         isl_map_free(currentAccessMap);
276         isl_map_free(newAccessMap);
277         return false;
278       }
279 
280       // We need to copy the isl_ids for the parameter dimensions to the new
281       // map. Without doing this the current map would have different
282       // ids then the new one, even though both are named identically.
283       for (unsigned i = 0; i < isl_map_dim(currentAccessMap, isl_dim_param);
284            i++) {
285         isl_id *id = isl_map_get_dim_id(currentAccessMap, isl_dim_param, i);
286         newAccessMap = isl_map_set_dim_id(newAccessMap, isl_dim_param, i, id);
287       }
288 
289       // Copy the old tuple id. This is necessary to retain the user pointer,
290       // that stores the reference to the ScopStmt this access belongs to.
291       isl_id *Id = isl_map_get_tuple_id(currentAccessMap, isl_dim_in);
292       newAccessMap = isl_map_set_tuple_id(newAccessMap, isl_dim_in, Id);
293 
294       if (!isl_map_has_equal_space(currentAccessMap, newAccessMap)) {
295         errs() << "JScop file contains access function with incompatible "
296                << "dimensions\n";
297         isl_map_free(currentAccessMap);
298         isl_map_free(newAccessMap);
299         return false;
300       }
301       if (isl_map_dim(newAccessMap, isl_dim_out) != 1) {
302         errs() << "New access map in JScop file should be single dimensional\n";
303         isl_map_free(currentAccessMap);
304         isl_map_free(newAccessMap);
305         return false;
306       }
307       if (!isl_map_is_equal(newAccessMap, currentAccessMap)) {
308         // Statistics.
309         ++NewAccessMapFound;
310         newAccessStrings.push_back(accesses.asCString());
311         MA->setNewAccessRelation(newAccessMap);
312       } else {
313         isl_map_free(newAccessMap);
314       }
315       isl_map_free(currentAccessMap);
316       memoryAccessIdx++;
317     }
318     statementIdx++;
319   }
320 
321   return false;
322 }
323 
324 void JSONImporter::getAnalysisUsage(AnalysisUsage &AU) const {
325   ScopPass::getAnalysisUsage(AU);
326   AU.addRequired<Dependences>();
327 }
328 Pass *polly::createJSONImporterPass() { return new JSONImporter(); }
329 
330 INITIALIZE_PASS_BEGIN(JSONExporter, "polly-export-jscop",
331                       "Polly - Export Scops as JSON"
332                       " (Writes a .jscop file for each Scop)",
333                       false, false);
334 INITIALIZE_PASS_DEPENDENCY(Dependences)
335 INITIALIZE_PASS_END(JSONExporter, "polly-export-jscop",
336                     "Polly - Export Scops as JSON"
337                     " (Writes a .jscop file for each Scop)",
338                     false, false)
339 
340 INITIALIZE_PASS_BEGIN(JSONImporter, "polly-import-jscop",
341                       "Polly - Import Scops from JSON"
342                       " (Reads a .jscop file for each Scop)",
343                       false, false);
344 INITIALIZE_PASS_DEPENDENCY(Dependences)
345 INITIALIZE_PASS_END(JSONImporter, "polly-import-jscop",
346                     "Polly - Import Scops from JSON"
347                     " (Reads a .jscop file for each Scop)",
348                     false, false)
349