Coverage Report

Created: 2017-10-03 07:32

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