Coverage Report

Created: 2019-04-25 15:07

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