Coverage Report

Created: 2017-11-23 03:11

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