Coverage Report

Created: 2017-08-21 19:50

/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
90
  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
91
static std::string getFileName(Scop &S, StringRef Suffix = "") {
89
91
  std::string FunctionName = S.getFunction().getName();
90
91
  std::string FileName = FunctionName + "___" + S.getNameStr() + ".jscop";
91
91
92
91
  if (Suffix != "")
93
52
    FileName += "." + Suffix.str();
94
91
95
91
  return FileName;
96
91
}
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
)
{0
116
0
      Array["sizes"].append("*");
117
0
      i++;
118
0
    }
119
0
    for (; 
i < SAI->getNumberOfDimensions()0
;
i++0
)
{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
  tool_output_file 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
)
{0
191
0
    F.os() << fileContent;
192
0
    F.os().close();
193
0
    if (
!F.os().has_error()0
)
{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
91
static bool importContext(Scop &S, Json::Value &JScop) {
213
91
  isl_set *OldContext = S.getContext().release();
214
91
215
91
  // Check if key 'context' is present.
216
91
  if (
!JScop.isMember("context")91
)
{1
217
1
    errs() << "JScop file has no key named 'context'.\n";
218
1
    isl_set_free(OldContext);
219
1
    return false;
220
91
  }
221
91
222
91
  isl_set *NewContext =
223
90
      isl_set_read_from_str(S.getIslCtx(), JScop["context"].asCString());
224
90
225
90
  // Check whether the context was parsed successfully.
226
90
  if (
!NewContext90
)
{1
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
90
  }
232
90
233
90
  // Check if the isl_set is a parameter set.
234
89
  
if (89
!isl_set_is_params(NewContext)89
)
{1
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
89
  }
240
89
241
89
  unsigned OldContextDim = isl_set_dim(OldContext, isl_dim_param);
242
88
  unsigned NewContextDim = isl_set_dim(NewContext, isl_dim_param);
243
88
244
88
  // Check if the imported context has the right number of parameters.
245
88
  if (
OldContextDim != NewContextDim88
)
{1
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
88
  }
253
88
254
139
  
for (unsigned i = 0; 87
i < OldContextDim139
;
i++52
)
{52
255
52
    isl_id *Id = isl_set_get_dim_id(OldContext, isl_dim_param, i);
256
52
    NewContext = isl_set_set_dim_id(NewContext, isl_dim_param, i, Id);
257
87
  }
258
87
259
87
  isl_set_free(OldContext);
260
87
  S.setContext(NewContext);
261
88
  return true;
262
91
}
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
87
static bool importSchedule(Scop &S, Json::Value &JScop, const Dependences &D) {
275
87
  StatementToIslMapTy NewSchedule;
276
87
277
87
  // Check if key 'statements' is present.
278
87
  if (
!JScop.isMember("statements")87
)
{2
279
2
    errs() << "JScop file has no key name 'statements'.\n";
280
2
    return false;
281
87
  }
282
87
283
87
  Json::Value statements = JScop["statements"];
284
85
285
85
  // Check whether the number of indices equals the number of statements
286
85
  if (
statements.size() != S.getSize()85
)
{2
287
2
    errs() << "The number of indices and the number of statements differ.\n";
288
2
    return false;
289
85
  }
290
85
291
85
  int Index = 0;
292
123
  for (ScopStmt &Stmt : S) {
293
123
    // Check if key 'schedule' is present.
294
123
    if (
!statements[Index].isMember("schedule")123
)
{1
295
1
      errs() << "Statement " << Index << " has no 'schedule' key.\n";
296
1
      for (auto Element : NewSchedule) {
297
0
        isl_map_free(Element.second);
298
1
      }
299
1
      return false;
300
123
    }
301
123
    Json::Value Schedule = statements[Index]["schedule"];
302
122
    assert(!Schedule.asString().empty() &&
303
122
           "Schedules that contain extension nodes require special handling.");
304
122
    isl_map *Map = isl_map_read_from_str(S.getIslCtx(), Schedule.asCString());
305
122
306
122
    // Check whether the schedule was parsed successfully
307
122
    if (
!Map122
)
{1
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
122
    }
315
122
316
122
    isl_space *Space = Stmt.getDomainSpace().release();
317
121
318
121
    // Copy the old tuple id. This is necessary to retain the user pointer,
319
121
    // that stores the reference to the ScopStmt this schedule belongs to.
320
121
    Map = isl_map_set_tuple_id(Map, isl_dim_in,
321
121
                               isl_space_get_tuple_id(Space, isl_dim_set));
322
190
    for (unsigned i = 0; 
i < isl_space_dim(Space, isl_dim_param)190
;
i++69
)
{69
323
69
      isl_id *Id = isl_space_get_dim_id(Space, isl_dim_param, i);
324
69
      Map = isl_map_set_dim_id(Map, isl_dim_param, i, Id);
325
121
    }
326
121
    isl_space_free(Space);
327
121
    NewSchedule[&Stmt] = Map;
328
121
    Index++;
329
121
  }
330
83
331
83
  // Check whether the new schedule is valid or not.
332
81
  
if (81
!D.isValidSchedule(S, &NewSchedule)81
)
{0
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
81
  }
339
81
340
81
  auto ScheduleMap = isl_union_map_empty(S.getParamSpace().release());
341
120
  for (ScopStmt &Stmt : S) {
342
120
    if (NewSchedule.find(&Stmt) != NewSchedule.end())
343
120
      ScheduleMap = isl_union_map_add_map(ScheduleMap, NewSchedule[&Stmt]);
344
120
    else
345
120
      ScheduleMap =
346
120
          isl_union_map_add_map(ScheduleMap, Stmt.getSchedule().release());
347
120
  }
348
81
349
81
  S.setSchedule(ScheduleMap);
350
81
351
81
  return true;
352
87
}
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
76
               std::vector<std::string> *NewAccessStrings = nullptr) {
365
76
  int StatementIdx = 0;
366
76
367
76
  // Check if key 'statements' is present.
368
76
  if (
!JScop.isMember("statements")76
)
{0
369
0
    errs() << "JScop file has no key name 'statements'.\n";
370
0
    return false;
371
76
  }
372
76
  Json::Value statements = JScop["statements"];
373
76
374
76
  // Check whether the number of indices equals the number of statements
375
76
  if (
statements.size() != S.getSize()76
)
{0
376
0
    errs() << "The number of indices and the number of statements differ.\n";
377
0
    return false;
378
76
  }
379
76
380
76
  
for (ScopStmt &Stmt : S) 76
{111
381
111
    int MemoryAccessIdx = 0;
382
111
383
111
    // Check if key 'accesses' is present.
384
111
    if (
!statements[StatementIdx].isMember("accesses")111
)
{1
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
111
    }
390
111
391
111
    // Check whether the number of indices equals the number of memory
392
111
    // accesses
393
110
    
if (110
Stmt.size() != statements[StatementIdx]["accesses"].size()110
)
{1
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
110
    }
399
110
400
109
    
for (MemoryAccess *MA : Stmt) 109
{242
401
242
      // Check if key 'relation' is present.
402
242
      Json::Value JsonMemoryAccess =
403
242
          statements[StatementIdx]["accesses"][MemoryAccessIdx];
404
242
      if (
!JsonMemoryAccess.isMember("relation")242
)
{1
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
242
      }
410
242
      Json::Value Accesses = JsonMemoryAccess["relation"];
411
241
      isl_map *NewAccessMap =
412
241
          isl_map_read_from_str(S.getIslCtx(), Accesses.asCString());
413
241
414
241
      // Check whether the access was parsed successfully
415
241
      if (
!NewAccessMap241
)
{1
416
1
        errs() << "The access was not parsed successfully by ISL.\n";
417
1
        return false;
418
241
      }
419
241
      isl_map *CurrentAccessMap = MA->getAccessRelation().release();
420
240
421
240
      // Check if the number of parameter change
422
240
      if (isl_map_dim(NewAccessMap, isl_dim_param) !=
423
240
          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
240
      }
429
240
430
240
      isl_id *NewOutId;
431
239
432
239
      // If the NewAccessMap has zero dimensions, it is the scalar access; it
433
239
      // must be the same as before.
434
239
      // If it has at least one dimension, it's an array access; search for
435
239
      // its ScopArrayInfo.
436
239
      if (
isl_map_dim(NewAccessMap, isl_dim_out) >= 1239
)
{230
437
230
        NewOutId = isl_map_get_tuple_id(NewAccessMap, isl_dim_out);
438
230
        auto *SAI = S.getArrayInfoByName(isl_id_get_name(NewOutId));
439
230
        isl_id *OutId = isl_map_get_tuple_id(CurrentAccessMap, isl_dim_out);
440
230
        auto *OutSAI = ScopArrayInfo::getFromId(isl::manage(OutId));
441
230
        if (
!SAI || 230
SAI->getElementType() != OutSAI->getElementType()229
)
{1
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
230
        }
449
230
        isl_id_free(NewOutId);
450
229
        NewOutId = SAI->getBasePtrId().release();
451
239
      } else {
452
9
        NewOutId = isl_map_get_tuple_id(CurrentAccessMap, isl_dim_out);
453
239
      }
454
239
455
239
      NewAccessMap = isl_map_set_tuple_id(NewAccessMap, isl_dim_out, NewOutId);
456
238
457
238
      if (
MA->isArrayKind()238
)
{175
458
175
        // We keep the old alignment, thus we cannot allow accesses to memory
459
175
        // locations that were not accessed before if the alignment of the
460
175
        // access is not the default alignment.
461
175
        bool SpecialAlignment = true;
462
175
        if (LoadInst *
LoadI175
= dyn_cast<LoadInst>(MA->getAccessInstruction()))
{72
463
72
          SpecialAlignment =
464
72
              LoadI->getAlignment() &&
465
63
              DL.getABITypeAlignment(LoadI->getType()) != LoadI->getAlignment();
466
175
        } else 
if (StoreInst *103
StoreI103
=
467
103
                       dyn_cast<StoreInst>(MA->getAccessInstruction())) {
468
103
          SpecialAlignment =
469
103
              StoreI->getAlignment() &&
470
103
              DL.getABITypeAlignment(StoreI->getValueOperand()->getType()) !=
471
103
                  StoreI->getAlignment();
472
175
        }
473
175
474
175
        if (
SpecialAlignment175
)
{1
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
)
{1
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
175
        }
490
238
      }
491
238
492
238
      // We need to copy the isl_ids for the parameter dimensions to the new
493
238
      // map. Without doing this the current map would have different
494
238
      // ids then the new one, even though both are named identically.
495
369
      
for (unsigned i = 0; 237
i < isl_map_dim(CurrentAccessMap, isl_dim_param)369
;
496
237
           
i++132
)
{132
497
132
        isl_id *Id = isl_map_get_dim_id(CurrentAccessMap, isl_dim_param, i);
498
132
        NewAccessMap = isl_map_set_dim_id(NewAccessMap, isl_dim_param, i, Id);
499
237
      }
500
237
501
237
      // Copy the old tuple id. This is necessary to retain the user pointer,
502
237
      // that stores the reference to the ScopStmt this access belongs to.
503
237
      isl_id *Id = isl_map_get_tuple_id(CurrentAccessMap, isl_dim_in);
504
237
      NewAccessMap = isl_map_set_tuple_id(NewAccessMap, isl_dim_in, Id);
505
237
506
237
      auto NewAccessDomain = isl_map_domain(isl_map_copy(NewAccessMap));
507
237
      auto CurrentAccessDomain = isl_map_domain(isl_map_copy(CurrentAccessMap));
508
237
509
237
      if (
!isl_set_has_equal_space(NewAccessDomain, CurrentAccessDomain)237
)
{0
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
237
      }
518
237
519
237
      NewAccessDomain =
520
237
          isl_set_intersect_params(NewAccessDomain, S.getContext().release());
521
237
      CurrentAccessDomain = isl_set_intersect_params(CurrentAccessDomain,
522
237
                                                     S.getContext().release());
523
237
524
237
      if (MA->isRead() &&
525
237
          isl_set_is_subset(CurrentAccessDomain, NewAccessDomain) ==
526
237
              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
237
      }
534
237
535
237
      isl_set_free(CurrentAccessDomain);
536
237
      isl_set_free(NewAccessDomain);
537
237
538
237
      if (
!isl_map_is_equal(NewAccessMap, CurrentAccessMap)237
)
{136
539
136
        // Statistics.
540
136
        ++NewAccessMapFound;
541
136
        if (NewAccessStrings)
542
136
          NewAccessStrings->push_back(Accesses.asCString());
543
136
        MA->setNewAccessRelation(isl::manage(NewAccessMap));
544
237
      } else {
545
101
        isl_map_free(NewAccessMap);
546
237
      }
547
237
      isl_map_free(CurrentAccessMap);
548
237
      MemoryAccessIdx++;
549
237
    }
550
109
    StatementIdx++;
551
104
  }
552
76
553
69
  return true;
554
76
}
555
556
/// Check whether @p SAI and @p Array represent the same array.
557
58
static bool areArraysEqual(ScopArrayInfo *SAI, Json::Value Array) {
558
58
  std::string Buffer;
559
58
  llvm::raw_string_ostream RawStringOstream(Buffer);
560
58
561
58
  // Check if key 'type' is present.
562
58
  if (
!Array.isMember("type")58
)
{1
563
1
    errs() << "Array has no key 'type'.\n";
564
1
    return false;
565
58
  }
566
58
567
58
  // Check if key 'sizes' is present.
568
57
  
if (57
!Array.isMember("sizes")57
)
{1
569
1
    errs() << "Array has no key 'sizes'.\n";
570
1
    return false;
571
57
  }
572
57
573
57
  // Check if key 'name' is present.
574
56
  
if (56
!Array.isMember("name")56
)
{1
575
1
    errs() << "Array has no key 'name'.\n";
576
1
    return false;
577
56
  }
578
56
579
55
  
if (55
SAI->getName() != Array["name"].asCString()55
)
580
0
    return false;
581
55
582
55
  
if (55
SAI->getNumberOfDimensions() != Array["sizes"].size()55
)
583
0
    return false;
584
55
585
73
  
for (unsigned i = 1; 55
i < Array["sizes"].size()73
;
i++18
)
{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
55
  }
591
55
592
55
  // Check if key 'type' differs from the current one or is not valid.
593
55
  SAI->getElementType()->print(RawStringOstream);
594
55
  if (
RawStringOstream.str() != Array["type"].asCString()55
)
{1
595
1
    errs() << "Array has not a valid type.\n";
596
1
    return false;
597
55
  }
598
55
599
54
  return true;
600
58
}
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
13
629
13
  errs() << "Textual representation can not be parsed: "
630
0
         << TypeTextRepresentation << "\n";
631
13
  return nullptr;
632
13
}
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
81
static bool importArrays(Scop &S, Json::Value &JScop) {
641
81
  Json::Value Arrays = JScop["arrays"];
642
81
  if (Arrays.size() == 0)
643
41
    return true;
644
81
645
81
  unsigned ArrayIdx = 0;
646
89
  for (auto &SAI : S.arrays()) {
647
89
    if (!SAI->isArrayKind())
648
31
      continue;
649
58
    
if (58
ArrayIdx + 1 > Arrays.size()58
)
{0
650
0
      errs() << "Not enough array entries in JScop file.\n";
651
0
      return false;
652
58
    }
653
58
    
if (58
!areArraysEqual(SAI, Arrays[ArrayIdx])58
)
{4
654
4
      errs() << "No match for array '" << SAI->getName() << "' in JScop.\n";
655
4
      return false;
656
58
    }
657
58
    ArrayIdx++;
658
54
  }
659
40
660
48
  
for (; 36
ArrayIdx < Arrays.size()48
;
ArrayIdx++12
)
{13
661
13
    auto &Array = Arrays[ArrayIdx];
662
13
    auto *ElementType =
663
13
        parseTextType(Array["type"].asCString(), S.getSE()->getContext());
664
13
    if (
!ElementType13
)
{0
665
0
      errs() << "Error while parsing element type for new array.\n";
666
0
      return false;
667
13
    }
668
13
    std::vector<unsigned> DimSizes;
669
29
    for (unsigned i = 0; 
i < Array["sizes"].size()29
;
i++16
)
{17
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
)
{1
674
1
        errs() << "The size at index " << i << " is =< 0.\n";
675
1
        return false;
676
17
      }
677
17
678
17
      DimSizes.push_back(Size);
679
16
    }
680
13
681
13
    auto NewSAI =
682
12
        S.createScopArrayInfo(ElementType, Array["name"].asCString(), DimSizes);
683
12
684
12
    if (
Array.isMember("allocation")12
)
{6
685
6
      NewSAI->setIsOnHeap(Array["allocation"].asString() == "heap");
686
12
    }
687
36
  }
688
36
689
35
  return true;
690
81
}
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
91
                       std::vector<std::string> *NewAccessStrings = nullptr) {
703
91
  std::string FileName = ImportDir + "/" + getFileName(S, ImportPostfix);
704
91
705
91
  std::string FunctionName = S.getFunction().getName();
706
91
  errs() << "Reading JScop '" << S.getNameStr() << "' in function '"
707
91
         << FunctionName << "' from '" << FileName << "'.\n";
708
91
  ErrorOr<std::unique_ptr<MemoryBuffer>> result =
709
91
      MemoryBuffer::getFile(FileName);
710
91
  std::error_code ec = result.getError();
711
91
712
91
  if (
ec91
)
{0
713
0
    errs() << "File could not be read: " << ec.message() << "\n";
714
0
    return false;
715
91
  }
716
91
717
91
  Json::Reader reader;
718
91
  Json::Value jscop;
719
91
720
91
  bool parsingSuccessful = reader.parse(result.get()->getBufferStart(), jscop);
721
91
722
91
  if (
!parsingSuccessful91
)
{0
723
0
    errs() << "JSCoP file could not be parsed\n";
724
0
    return false;
725
91
  }
726
91
727
91
  bool Success = importContext(S, jscop);
728
91
729
91
  if (!Success)
730
4
    return false;
731
91
732
91
  Success = importSchedule(S, jscop, D);
733
87
734
87
  if (!Success)
735
6
    return false;
736
87
737
87
  Success = importArrays(S, jscop);
738
81
739
81
  if (!Success)
740
5
    return false;
741
81
742
81
  Success = importAccesses(S, jscop, DL, NewAccessStrings);
743
76
744
76
  if (!Success)
745
7
    return false;
746
69
  return true;
747
91
}
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
91
bool JSONImporter::runOnScop(Scop &S) {
782
91
  const Dependences &D =
783
91
      getAnalysis<DependenceInfo>().getDependences(Dependences::AL_Statement);
784
91
  const DataLayout &DL = S.getFunction().getParent()->getDataLayout();
785
91
786
91
  if (!importScop(S, D, DL, &NewAccessStrings))
787
22
    report_fatal_error("Tried to import a malformed jscop file.");
788
91
789
69
  return false;
790
91
}
791
792
90
void JSONImporter::getAnalysisUsage(AnalysisUsage &AU) const {
793
90
  ScopPass::getAnalysisUsage(AU);
794
90
  AU.addRequired<DependenceInfo>();
795
90
}
796
797
0
Pass *polly::createJSONImporterPass() { return new JSONImporter(); }
798
799
PreservedAnalyses JSONImportPass::run(Scop &S, ScopAnalysisManager &SAM,
800
                                      ScopStandardAnalysisResults &SAR,
801
0
                                      SPMUpdater &) {
802
0
  const Dependences &D =
803
0
      SAM.getResult<DependenceAnalysis>(S, SAR).getDependences(
804
0
          Dependences::AL_Statement);
805
0
  const DataLayout &DL = S.getFunction().getParent()->getDataLayout();
806
0
807
0
  if (!importScop(S, D, DL))
808
0
    report_fatal_error("Tried to import a malformed jscop file.");
809
0
810
0
  // This invalidates all analyses on Scop.
811
0
  PreservedAnalyses PA;
812
0
  PA.preserveSet<AllAnalysesOn<Module>>();
813
0
  PA.preserveSet<AllAnalysesOn<Function>>();
814
0
  PA.preserveSet<AllAnalysesOn<Loop>>();
815
0
  return PA;
816
0
}
817
818
41.9k
INITIALIZE_PASS_BEGIN41.9k
(JSONExporter, "polly-export-jscop",41.9k
819
41.9k
                      "Polly - Export Scops as JSON"
820
41.9k
                      " (Writes a .jscop file for each Scop)",
821
41.9k
                      false, false);
822
41.9k
INITIALIZE_PASS_DEPENDENCY(DependenceInfo)
823
41.9k
INITIALIZE_PASS_END(JSONExporter, "polly-export-jscop",
824
                    "Polly - Export Scops as JSON"
825
                    " (Writes a .jscop file for each Scop)",
826
                    false, false)
827
828
41.9k
INITIALIZE_PASS_BEGIN41.9k
(JSONImporter, "polly-import-jscop",41.9k
829
41.9k
                      "Polly - Import Scops from JSON"
830
41.9k
                      " (Reads a .jscop file for each Scop)",
831
41.9k
                      false, false);
832
41.9k
INITIALIZE_PASS_DEPENDENCY(DependenceInfo)
833
41.9k
INITIALIZE_PASS_END(JSONImporter, "polly-import-jscop",
834
                    "Polly - Import Scops from JSON"
835
                    " (Reads a .jscop file for each Scop)",
836
                    false, false)