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/DependenceInfo.h"
16 #include "polly/Options.h"
17 #include "polly/ScopInfo.h"
18 #include "polly/ScopPass.h"
19 #include "polly/Support/ScopLocation.h"
20 #include "llvm/ADT/Statistic.h"
21 #include "llvm/Analysis/RegionInfo.h"
22 #include "llvm/IR/Module.h"
23 #include "llvm/Support/FileSystem.h"
24 #include "llvm/Support/MemoryBuffer.h"
25 #include "llvm/Support/ToolOutputFile.h"
26 #include "isl/constraint.h"
27 #include "isl/map.h"
28 #include "isl/printer.h"
29 #include "isl/set.h"
30 #include "json/reader.h"
31 #include "json/writer.h"
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   explicit JSONExporter() : ScopPass(ID) {}
59 
60   std::string getFileName(Scop &S) const;
61   Json::Value getJSON(Scop &S) const;
62   virtual bool runOnScop(Scop &S);
63   void printScop(raw_ostream &OS, Scop &S) const;
64   void getAnalysisUsage(AnalysisUsage &AU) const;
65 };
66 
67 struct JSONImporter : public ScopPass {
68   static char ID;
69   std::vector<std::string> newAccessStrings;
70   explicit JSONImporter() : ScopPass(ID) {}
71 
72   std::string getFileName(Scop &S) const;
73   virtual bool runOnScop(Scop &S);
74   void printScop(raw_ostream &OS, Scop &S) const;
75   void getAnalysisUsage(AnalysisUsage &AU) const;
76 };
77 }
78 
79 char JSONExporter::ID = 0;
80 std::string JSONExporter::getFileName(Scop &S) const {
81   std::string FunctionName = S.getRegion().getEntry()->getParent()->getName();
82   std::string FileName = FunctionName + "___" + S.getNameStr() + ".jscop";
83   return FileName;
84 }
85 
86 void JSONExporter::printScop(raw_ostream &OS, Scop &S) const { S.print(OS); }
87 
88 Json::Value JSONExporter::getJSON(Scop &S) const {
89   Json::Value root;
90   unsigned LineBegin, LineEnd;
91   std::string FileName;
92 
93   getDebugLocation(&S.getRegion(), LineBegin, LineEnd, FileName);
94   std::string Location;
95   if (LineBegin != (unsigned)-1)
96     Location = FileName + ":" + std::to_string(LineBegin) + "-" +
97                std::to_string(LineEnd);
98 
99   root["name"] = S.getRegion().getNameStr();
100   root["context"] = S.getContextStr();
101   if (LineBegin != (unsigned)-1)
102     root["location"] = Location;
103   root["statements"];
104 
105   for (ScopStmt &Stmt : S) {
106     Json::Value statement;
107 
108     statement["name"] = Stmt.getBaseName();
109     statement["domain"] = Stmt.getDomainStr();
110     statement["schedule"] = Stmt.getScheduleStr();
111     statement["accesses"];
112 
113     for (MemoryAccess *MA : Stmt) {
114       Json::Value access;
115 
116       access["kind"] = MA->isRead() ? "read" : "write";
117       access["relation"] = MA->getOriginalAccessRelationStr();
118 
119       statement["accesses"].append(access);
120     }
121 
122     root["statements"].append(statement);
123   }
124 
125   return root;
126 }
127 
128 bool JSONExporter::runOnScop(Scop &S) {
129   Region &R = S.getRegion();
130 
131   std::string FileName = ImportDir + "/" + getFileName(S);
132 
133   Json::Value jscop = getJSON(S);
134   Json::StyledWriter writer;
135   std::string fileContent = writer.write(jscop);
136 
137   // Write to file.
138   std::error_code EC;
139   tool_output_file F(FileName, EC, llvm::sys::fs::F_Text);
140 
141   std::string FunctionName = R.getEntry()->getParent()->getName();
142   errs() << "Writing JScop '" << R.getNameStr() << "' in function '"
143          << FunctionName << "' to '" << FileName << "'.\n";
144 
145   if (!EC) {
146     F.os() << fileContent;
147     F.os().close();
148     if (!F.os().has_error()) {
149       errs() << "\n";
150       F.keep();
151       return false;
152     }
153   }
154 
155   errs() << "  error opening file for writing!\n";
156   F.os().clear_error();
157 
158   return false;
159 }
160 
161 void JSONExporter::getAnalysisUsage(AnalysisUsage &AU) const {
162   AU.setPreservesAll();
163   AU.addRequired<ScopInfo>();
164 }
165 
166 Pass *polly::createJSONExporterPass() { return new JSONExporter(); }
167 
168 char JSONImporter::ID = 0;
169 std::string JSONImporter::getFileName(Scop &S) const {
170   std::string FunctionName = S.getRegion().getEntry()->getParent()->getName();
171   std::string FileName = FunctionName + "___" + S.getNameStr() + ".jscop";
172 
173   if (ImportPostfix != "")
174     FileName += "." + ImportPostfix;
175 
176   return FileName;
177 }
178 
179 void JSONImporter::printScop(raw_ostream &OS, Scop &S) const {
180   S.print(OS);
181   for (std::vector<std::string>::const_iterator I = newAccessStrings.begin(),
182                                                 E = newAccessStrings.end();
183        I != E; I++)
184     OS << "New access function '" << *I << "'detected in JSCOP file\n";
185 }
186 
187 typedef Dependences::StatementToIslMapTy StatementToIslMapTy;
188 
189 bool JSONImporter::runOnScop(Scop &S) {
190   Region &R = S.getRegion();
191   const Dependences &D = getAnalysis<DependenceInfo>().getDependences();
192   const DataLayout &DL =
193       S.getRegion().getEntry()->getParent()->getParent()->getDataLayout();
194 
195   std::string FileName = ImportDir + "/" + getFileName(S);
196 
197   std::string FunctionName = R.getEntry()->getParent()->getName();
198   errs() << "Reading JScop '" << R.getNameStr() << "' in function '"
199          << FunctionName << "' from '" << FileName << "'.\n";
200   ErrorOr<std::unique_ptr<MemoryBuffer>> result =
201       MemoryBuffer::getFile(FileName);
202   std::error_code ec = result.getError();
203 
204   if (ec) {
205     errs() << "File could not be read: " << ec.message() << "\n";
206     return false;
207   }
208 
209   Json::Reader reader;
210   Json::Value jscop;
211 
212   bool parsingSuccessful = reader.parse(result.get()->getBufferStart(), jscop);
213 
214   if (!parsingSuccessful) {
215     errs() << "JSCoP file could not be parsed\n";
216     return false;
217   }
218 
219   isl_set *OldContext = S.getContext();
220   isl_set *NewContext =
221       isl_set_read_from_str(S.getIslCtx(), jscop["context"].asCString());
222 
223   for (unsigned i = 0; i < isl_set_dim(OldContext, isl_dim_param); i++) {
224     isl_id *id = isl_set_get_dim_id(OldContext, isl_dim_param, i);
225     NewContext = isl_set_set_dim_id(NewContext, isl_dim_param, i, id);
226   }
227 
228   isl_set_free(OldContext);
229   S.setContext(NewContext);
230 
231   StatementToIslMapTy NewSchedule;
232 
233   int index = 0;
234 
235   for (ScopStmt &Stmt : S) {
236     Json::Value schedule = jscop["statements"][index]["schedule"];
237     isl_map *m = isl_map_read_from_str(S.getIslCtx(), schedule.asCString());
238     isl_space *Space = Stmt.getDomainSpace();
239 
240     // Copy the old tuple id. This is necessary to retain the user pointer,
241     // that stores the reference to the ScopStmt this schedule belongs to.
242     m = isl_map_set_tuple_id(m, isl_dim_in,
243                              isl_space_get_tuple_id(Space, isl_dim_set));
244     for (unsigned i = 0; i < isl_space_dim(Space, isl_dim_param); i++) {
245       isl_id *id = isl_space_get_dim_id(Space, isl_dim_param, i);
246       m = isl_map_set_dim_id(m, isl_dim_param, i, id);
247     }
248     isl_space_free(Space);
249     NewSchedule[&Stmt] = m;
250     index++;
251   }
252 
253   if (!D.isValidSchedule(S, &NewSchedule)) {
254     errs() << "JScop file contains a schedule that changes the "
255            << "dependences. Use -disable-polly-legality to continue anyways\n";
256     for (StatementToIslMapTy::iterator SI = NewSchedule.begin(),
257                                        SE = NewSchedule.end();
258          SI != SE; ++SI)
259       isl_map_free(SI->second);
260     return false;
261   }
262 
263   for (ScopStmt &Stmt : S) {
264     if (NewSchedule.find(&Stmt) != NewSchedule.end())
265       Stmt.setSchedule(NewSchedule[&Stmt]);
266   }
267 
268   int statementIdx = 0;
269   for (ScopStmt &Stmt : S) {
270     int memoryAccessIdx = 0;
271     for (MemoryAccess *MA : Stmt) {
272       Json::Value accesses = jscop["statements"][statementIdx]["accesses"]
273                                   [memoryAccessIdx]["relation"];
274       isl_map *newAccessMap =
275           isl_map_read_from_str(S.getIslCtx(), accesses.asCString());
276       isl_map *currentAccessMap = MA->getAccessRelation();
277 
278       if (isl_map_dim(newAccessMap, isl_dim_param) !=
279           isl_map_dim(currentAccessMap, isl_dim_param)) {
280         errs() << "JScop file changes the number of parameter dimensions\n";
281         isl_map_free(currentAccessMap);
282         isl_map_free(newAccessMap);
283         return false;
284       }
285 
286       isl_id *OutId = isl_map_get_tuple_id(currentAccessMap, isl_dim_out);
287       newAccessMap = isl_map_set_tuple_id(newAccessMap, isl_dim_out, OutId);
288 
289       // We keep the old alignment, thus we cannot allow accesses to memory
290       // locations that were not accessed before if the alignment of the access
291       // is not the default alignment.
292       bool SpecialAlignment = true;
293       if (LoadInst *LoadI = dyn_cast<LoadInst>(MA->getAccessInstruction())) {
294         SpecialAlignment =
295             DL.getABITypeAlignment(LoadI->getType()) != LoadI->getAlignment();
296       } else if (StoreInst *StoreI =
297                      dyn_cast<StoreInst>(MA->getAccessInstruction())) {
298         SpecialAlignment =
299             DL.getABITypeAlignment(StoreI->getValueOperand()->getType()) !=
300             StoreI->getAlignment();
301       }
302 
303       if (SpecialAlignment) {
304         isl_set *newAccessSet = isl_map_range(isl_map_copy(newAccessMap));
305         isl_set *currentAccessSet =
306             isl_map_range(isl_map_copy(currentAccessMap));
307         bool isSubset = isl_set_is_subset(newAccessSet, currentAccessSet);
308         isl_set_free(newAccessSet);
309         isl_set_free(currentAccessSet);
310 
311         if (!isSubset) {
312           errs() << "JScop file changes the accessed memory\n";
313           isl_map_free(currentAccessMap);
314           isl_map_free(newAccessMap);
315           return false;
316         }
317       }
318 
319       // We need to copy the isl_ids for the parameter dimensions to the new
320       // map. Without doing this the current map would have different
321       // ids then the new one, even though both are named identically.
322       for (unsigned i = 0; i < isl_map_dim(currentAccessMap, isl_dim_param);
323            i++) {
324         isl_id *id = isl_map_get_dim_id(currentAccessMap, isl_dim_param, i);
325         newAccessMap = isl_map_set_dim_id(newAccessMap, isl_dim_param, i, id);
326       }
327 
328       // Copy the old tuple id. This is necessary to retain the user pointer,
329       // that stores the reference to the ScopStmt this access belongs to.
330       isl_id *Id = isl_map_get_tuple_id(currentAccessMap, isl_dim_in);
331       newAccessMap = isl_map_set_tuple_id(newAccessMap, isl_dim_in, Id);
332 
333       if (!isl_map_has_equal_space(currentAccessMap, newAccessMap)) {
334         errs() << "JScop file contains access function with incompatible "
335                << "dimensions\n";
336         isl_map_free(currentAccessMap);
337         isl_map_free(newAccessMap);
338         return false;
339       }
340       if (isl_map_dim(newAccessMap, isl_dim_out) != 1) {
341         errs() << "New access map in JScop file should be single dimensional\n";
342         isl_map_free(currentAccessMap);
343         isl_map_free(newAccessMap);
344         return false;
345       }
346 
347       auto NewAccessDomain = isl_map_domain(isl_map_copy(newAccessMap));
348       auto CurrentAccessDomain = isl_map_domain(isl_map_copy(currentAccessMap));
349 
350       NewAccessDomain =
351           isl_set_intersect_params(NewAccessDomain, S.getContext());
352       CurrentAccessDomain =
353           isl_set_intersect_params(CurrentAccessDomain, S.getContext());
354 
355       if (isl_set_is_subset(CurrentAccessDomain, NewAccessDomain) ==
356           isl_bool_false) {
357         errs() << "Mapping not defined for all iteration domain elements\n";
358         isl_set_free(CurrentAccessDomain);
359         isl_set_free(NewAccessDomain);
360         isl_map_free(currentAccessMap);
361         isl_map_free(newAccessMap);
362         return false;
363       }
364 
365       isl_set_free(CurrentAccessDomain);
366       isl_set_free(NewAccessDomain);
367 
368       if (!isl_map_is_equal(newAccessMap, currentAccessMap)) {
369         // Statistics.
370         ++NewAccessMapFound;
371         newAccessStrings.push_back(accesses.asCString());
372         MA->setNewAccessRelation(newAccessMap);
373       } else {
374         isl_map_free(newAccessMap);
375       }
376       isl_map_free(currentAccessMap);
377       memoryAccessIdx++;
378     }
379     statementIdx++;
380   }
381 
382   return false;
383 }
384 
385 void JSONImporter::getAnalysisUsage(AnalysisUsage &AU) const {
386   ScopPass::getAnalysisUsage(AU);
387   AU.addRequired<DependenceInfo>();
388 }
389 Pass *polly::createJSONImporterPass() { return new JSONImporter(); }
390 
391 INITIALIZE_PASS_BEGIN(JSONExporter, "polly-export-jscop",
392                       "Polly - Export Scops as JSON"
393                       " (Writes a .jscop file for each Scop)",
394                       false, false);
395 INITIALIZE_PASS_DEPENDENCY(DependenceInfo)
396 INITIALIZE_PASS_END(JSONExporter, "polly-export-jscop",
397                     "Polly - Export Scops as JSON"
398                     " (Writes a .jscop file for each Scop)",
399                     false, false)
400 
401 INITIALIZE_PASS_BEGIN(JSONImporter, "polly-import-jscop",
402                       "Polly - Import Scops from JSON"
403                       " (Reads a .jscop file for each Scop)",
404                       false, false);
405 INITIALIZE_PASS_DEPENDENCY(DependenceInfo)
406 INITIALIZE_PASS_END(JSONImporter, "polly-import-jscop",
407                     "Polly - Import Scops from JSON"
408                     " (Reads a .jscop file for each Scop)",
409                     false, false)
410