File: BuildEngineCommand.cpp

package info (click to toggle)
swiftlang 6.0.3-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 2,519,992 kB
  • sloc: cpp: 9,107,863; ansic: 2,040,022; asm: 1,135,751; python: 296,500; objc: 82,456; f90: 60,502; lisp: 34,951; pascal: 19,946; sh: 18,133; perl: 7,482; ml: 4,937; javascript: 4,117; makefile: 3,840; awk: 3,535; xml: 914; fortran: 619; cs: 573; ruby: 573
file content (523 lines) | stat: -rw-r--r-- 16,277 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
//===-- BuildEngineCommand.cpp --------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//

#include "llbuild/Commands/Commands.h"

#include "llbuild/Basic/ExecutionQueue.h"
#include "llbuild/Basic/LLVM.h"
#include "llbuild/Core/BuildEngine.h"
#include "llbuild/Evo/EvoEngine.h"

#include "llvm/Support/raw_ostream.h"

#include <cassert>
#include <cmath>
#include <cstring>
#include <cstdlib>
#include <functional>
#include <iostream>
#include <memory>
#include <mutex>

using namespace llbuild;
using namespace llbuild::commands;

#pragma mark - Ackermann Build Command

namespace {

#ifndef NDEBUG
static uint64_t ack(int m, int n) {
  // Memoize using an array of growable vectors.
  std::vector<std::vector<int>> memoTable(m+1);

  std::function<int(int,int)> ack_internal;
  ack_internal = [&] (int m, int n) {
    assert(m >= 0 && n >= 0);
    auto& memoRow = memoTable[m];
    if (size_t(n) >= memoRow.size())
        memoRow.resize(n + 1);
    if (memoRow[n] != 0)
      return memoRow[n];

    int result;
    if (m == 0) {
      result = n + 1;
    } else if (n == 0) {
      result = ack_internal(m - 1, 1);
    } else {
      result = ack_internal(m - 1, ack_internal(m, n - 1));
    };

    memoRow[n] = result;
    return result;
  };

  return ack_internal(m, n);
}
#endif

static int32_t intFromValue(const core::ValueType& value) {
  assert(value.size() == 4);
  return ((value[0] << 0) |
          (value[1] << 8) |
          (value[2] << 16) |
          (value[3] << 24));
}
static core::ValueType intToValue(int32_t value) {
  std::vector<uint8_t> result(4);
  result[0] = (value >> 0) & 0xFF;
  result[1] = (value >> 8) & 0xFF;
  result[2] = (value >> 16) & 0xFF;
  result[3] = (value >> 24) & 0xFF;
  return result;
}

/// Key representation used in Ackermann build.
struct AckermannKey {
  /// The Ackermann number this key represents.
  int m, n;

  /// Create a key representing the given Ackermann number.
  AckermannKey(int m, int n) : m(m), n(n) {}

  /// Create an Ackermann key from the encoded representation.
  AckermannKey(const core::KeyType& key) {
      auto keyString = StringRef(key.str());
      assert(keyString.startswith("ack(") && keyString.endswith(")"));
      auto arguments = keyString.split("(").second.split(")").first.split(",");
      m = 0;
      n = 0;
      (void)arguments.first.getAsInteger(10, m);
      (void)arguments.second.getAsInteger(10, n);
      assert(m >= 0 && m < 4);
      assert(n >= 0);
  }

  /// Convert an Ackermann key to its encoded representation.
  operator core::KeyType() const {
    char inputKey[32];
    snprintf(inputKey, sizeof(inputKey), "ack(%d,%d)", m, n);
    return inputKey;
  }
};

/// Value representation used in Ackermann build.
struct AckermannValue {
  int value;

  /// Create a value for 0.
  AckermannValue() : value(0) { }

  /// Create a value from an integer.
  AckermannValue(int value) : value(value) { }

  /// Create a value from the encoded representation.
  AckermannValue(const core::ValueType& value) : value(intFromValue(value)) { }

  /// Convert a value to its encoded representation.
  operator core::ValueType() const {
    return intToValue(value);
  }

  /// Convert a wrapped value to its actual value.
  operator int() const {
    return value;
  }
};
    
struct AckermannTask : core::Task {
  int m, n;
  AckermannValue recursiveResultA = {};
  AckermannValue recursiveResultB = {};

  AckermannTask(core::BuildEngine& engine, int m, int n) : m(m), n(n) {
  }

  /// Called when the task is started.
  virtual void start(core::TaskInterface ti) override {
    // Request the first recursive result, if necessary.
    if (m == 0) {
      ;
    } else if (n == 0) {
      ti.request(AckermannKey(m-1, 1), 0);
    } else {
      ti.request(AckermannKey(m, n-1), 0);
    }
  }

  /// Called when a task’s requested input is available.
  virtual void provideValue(core::TaskInterface ti, uintptr_t inputID,
                            const core::ValueType& value) override {
    if (inputID == 0) {
      recursiveResultA = value;

      // Request the second recursive result, if needed.
      if (m != 0 && n != 0) {
        ti.request(AckermannKey(m-1, recursiveResultA), 1);
      }
    } else {
      assert(inputID == 1 && "invalid input ID");
      recursiveResultB = value;
    }
  }

  /// Called when all inputs are available.
  virtual void inputsAvailable(core::TaskInterface ti) override {
    if (m == 0) {
      ti.complete(AckermannValue(n + 1));
      return;
    }

    assert(recursiveResultA != 0);
    if (n == 0) {
      ti.complete(recursiveResultA);
      return;
    }

    assert(recursiveResultB != 0);
    ti.complete(recursiveResultB);
  }
};

static int runAckermannBuild(int m, int n, int recomputeCount,
                             const std::string& traceFilename,
                             const std::string& dumpGraphPath) {
  // Compute the value of ackermann(M, N) using the build system.
  assert(m >= 0 && m < 4);
  assert(n >= 0);

  // Define the delegate which will dynamically construct rules of the form
  // "ack(M,N)".
  class AckermannDelegate : public core::BuildEngineDelegate, public basic::ExecutionQueueDelegate {
    class AckermannRule : public core::Rule {
    public:
      AckermannRule(const core::KeyType& key) : core::Rule(key) { }
      core::Task* createTask(core::BuildEngine& engine) override {
        auto k = AckermannKey(key);
        return new AckermannTask(engine, k.m, k.n);
      }
      bool isResultValid(core::BuildEngine&, const core::ValueType&) override {
        return true;
      }
    };

  public:
    int numRules = 0;

    /// Get the rule to use for the given Key.
    virtual std::unique_ptr<core::Rule> lookupRule(const core::KeyType& keyData) override {
      ++numRules;
      return std::unique_ptr<core::Rule>(new AckermannRule(keyData));
    }

    /// Called when a cycle is detected by the build engine and it cannot make
    /// forward progress.
    virtual void cycleDetected(const std::vector<core::Rule*>& items) override {
      assert(0 && "unexpected cycle!");
    }

    /// Called when a fatal error is encountered by the build engine.
    virtual void error(const Twine &message) override {
      assert(0 && ("error:" + message.str()).c_str());
    }

    void processStarted(basic::ProcessContext*, basic::ProcessHandle, llbuild_pid_t) override { }
    void processHadError(basic::ProcessContext*, basic::ProcessHandle, const Twine&) override { }
    void processHadOutput(basic::ProcessContext*, basic::ProcessHandle, StringRef) override { }
    void processFinished(basic::ProcessContext*, basic::ProcessHandle, const basic::ProcessResult&) override { }
    void queueJobStarted(basic::JobDescriptor*) override { }
    void queueJobFinished(basic::JobDescriptor*) override { }

    std::unique_ptr<basic::ExecutionQueue> createExecutionQueue() override {
      return createSerialQueue(*this, nullptr);
    }
  };
  AckermannDelegate delegate;
  core::BuildEngine engine(delegate);

  // Enable tracing, if requested.
  if (!traceFilename.empty()) {
    std::string error;
    if (!engine.enableTracing(traceFilename, &error)) {
      fprintf(stderr, "error: %s: unable to enable tracing: %s\n",
              getProgramName(), error.c_str());
      return 1;
    }
  }

  auto key = AckermannKey(m, n);
  auto result = AckermannValue(engine.build(key));
  llvm::outs() << "ack(" << m << ", " << n << ") = " << result << "\n";
  if (n < 10) {
#ifndef NDEBUG
    int expected = ack(m, n);
    assert(result == expected);
#endif
  }
  llvm::outs() << "... computed using " << delegate.numRules << " rules\n";

  if (!dumpGraphPath.empty()) {
    engine.dumpGraphToFile(dumpGraphPath);
  }

  // Recompute the result as many times as requested.
  for (int i = 0; i != recomputeCount; ++i) {
    auto recomputedResult = AckermannValue(engine.build(key));
    if (recomputedResult != result)
      abort();
  }

  return 0;
}


static int runEvoAckermann(int m, int n, int recomputeCount,
                           const std::string& traceFilename,
                           const std::string& dumpGraphPath) {
  // Compute the value of ackermann(M, N) using the evo build system.
  assert(m >= 0 && m < 4);
  assert(n >= 0);

  // Define the delegate which will dynamically construct rules of the form
  // "ack(M,N)".
  class AckermannDelegate : public core::BuildEngineDelegate, public basic::ExecutionQueueDelegate {
    class AckermannRule : public evo::EvoRule {
    public:
      AckermannRule(const core::KeyType& key) : EvoRule(key) { }
      bool isResultValid(core::BuildEngine&, const core::ValueType&) override {
        return true;
      }

      core::ValueType run(evo::EvoEngine& engine) override {
        auto k = AckermannKey(key);
        auto m = k.m;
        auto n = k.n;

        if (m == 0) {
          return AckermannValue(n + 1);
        }

        if (n == 0) {
          return engine.wait(engine.request(AckermannKey(m - 1, 1)));
        }

        AckermannValue v = engine.wait(engine.request(AckermannKey(m, n - 1)));
        return engine.wait(engine.request(AckermannKey(m - 1, v)));
      }
    };

  public:
    int numRules = 0;

    /// Get the rule to use for the given Key.
    virtual std::unique_ptr<core::Rule> lookupRule(const core::KeyType& keyData) override {
      ++numRules;
      return std::unique_ptr<core::Rule>(new AckermannRule(keyData));
    }

    /// Called when a cycle is detected by the build engine and it cannot make
    /// forward progress.
    virtual void cycleDetected(const std::vector<core::Rule*>& items) override {
      assert(0 && "unexpected cycle!");
    }

    /// Called when a fatal error is encountered by the build engine.
    virtual void error(const Twine &message) override {
      assert(0 && ("error:" + message.str()).c_str());
    }

    void processStarted(basic::ProcessContext*, basic::ProcessHandle, llbuild_pid_t) override { }
    void processHadError(basic::ProcessContext*, basic::ProcessHandle, const Twine&) override { }
    void processHadOutput(basic::ProcessContext*, basic::ProcessHandle, StringRef) override { }
    void processFinished(basic::ProcessContext*, basic::ProcessHandle, const basic::ProcessResult&) override { }
    void queueJobStarted(basic::JobDescriptor*) override { }
    void queueJobFinished(basic::JobDescriptor*) override { }

    std::unique_ptr<basic::ExecutionQueue> createExecutionQueue() override {
      return createSerialQueue(*this, nullptr);
    }
  };
  AckermannDelegate delegate;
  core::BuildEngine engine(delegate);

  // Enable tracing, if requested.
  if (!traceFilename.empty()) {
    std::string error;
    if (!engine.enableTracing(traceFilename, &error)) {
      fprintf(stderr, "error: %s: unable to enable tracing: %s\n",
              getProgramName(), error.c_str());
      return 1;
    }
  }

  auto key = AckermannKey(m, n);
  auto result = AckermannValue(engine.build(key));
  llvm::outs() << "ack(" << m << ", " << n << ") = " << result << "\n";
  if (n < 10) {
#ifndef NDEBUG
    int expected = ack(m, n);
    assert(result == expected);
#endif
  }
  llvm::outs() << "... computed using " << delegate.numRules << " rules\n";

  if (!dumpGraphPath.empty()) {
    engine.dumpGraphToFile(dumpGraphPath);
  }

  // Recompute the result as many times as requested.
  for (int i = 0; i != recomputeCount; ++i) {
    auto recomputedResult = AckermannValue(engine.build(key));
    if (recomputedResult != result)
      abort();
  }

  return 0;
}



static void ackermannUsage(std::string cmd) {
  int optionWidth = 20;
  fprintf(stderr, "Usage: %s buildengine %s [options] <M> <N>\n",
          getProgramName(), cmd.c_str());
  fprintf(stderr, "\nOptions:\n");
  fprintf(stderr, "  %-*s %s\n", optionWidth, "--help",
          "show this help message and exit");
  fprintf(stderr, "  %-*s %s\n", optionWidth, "--dump-graph <PATH>",
          "dump build graph to PATH in Graphviz DOT format");
  fprintf(stderr, "  %-*s %s\n", optionWidth, "--recompute <N>",
          "recompute the result N times, to stress dependency checking");
  fprintf(stderr, "  %-*s %s\n", optionWidth, "--trace <PATH>",
          "trace build engine operation to PATH");
  ::exit(1);
}

static int executeAckermannCommand(std::string cmd, std::vector<std::string> args) {
  int recomputeCount = 0;
  std::string dumpGraphPath, traceFilename;
  while (!args.empty() && args[0][0] == '-') {
    const std::string option = args[0];
    args.erase(args.begin());

    if (option == "--")
      break;

    if (option == "--help") {
      ackermannUsage(cmd);
    } else if (option == "--recompute") {
      if (args.empty()) {
        fprintf(stderr, "error: %s: missing argument to '%s'\n\n",
                getProgramName(), option.c_str());
        ackermannUsage(cmd);
      }
      char *end;
      recomputeCount = ::strtol(args[0].c_str(), &end, 10);
      if (*end != '\0') {
        fprintf(stderr, "error: %s: invalid argument to '%s'\n\n",
                getProgramName(), option.c_str());
        ackermannUsage(cmd);
      }
      args.erase(args.begin());
    } else if (option == "--dump-graph") {
      if (args.empty()) {
        fprintf(stderr, "error: %s: missing argument to '%s'\n\n",
                getProgramName(), option.c_str());
        ackermannUsage(cmd);
      }
      dumpGraphPath = args[0];
      args.erase(args.begin());
    } else if (option == "--trace") {
      if (args.empty()) {
        fprintf(stderr, "error: %s: missing argument to '%s'\n\n",
                getProgramName(), option.c_str());
        ackermannUsage(cmd);
      }
      traceFilename = args[0];
      args.erase(args.begin());
    } else {
      fprintf(stderr, "error: %s: invalid option: '%s'\n\n",
              getProgramName(), option.c_str());
      ackermannUsage(cmd);
    }
  }

  if (args.size() != 2) {
    fprintf(stderr, "error: %s: invalid number of arguments\n", getProgramName());
    ackermannUsage(cmd);
  }

  const char *str = args[0].c_str();
  int m = ::strtol(str, (char**)&str, 10);
  if (*str != '\0') {
    fprintf(stderr, "error: %s: invalid argument '%s' (expected integer)\n",
            getProgramName(), args[0].c_str());
    return 1;
  }
  str = args[1].c_str();
  int n = ::strtol(str, (char**)&str, 10);
  if (*str != '\0') {
    fprintf(stderr, "error: %s: invalid argument '%s' (expected integer)\n",
            getProgramName(), args[1].c_str());
    return 1;
  }

  if (m >= 4) {
    fprintf(stderr, "error: %s: invalid argument M = '%d' (too large)\n",
            getProgramName(), m);
    return 1;
  }

  if (n >= 1024) {
    fprintf(stderr, "error: %s: invalid argument N = '%d' (too large)\n",
            getProgramName(), n);
    return 1;
  }

  if (cmd == "evo") {
    return runEvoAckermann(m, n, recomputeCount, traceFilename, dumpGraphPath);
  }

  return runAckermannBuild(m, n, recomputeCount, traceFilename, dumpGraphPath);
}



}

#pragma mark - Build Engine Top-Level Command

static void usage() {
  fprintf(stderr, "Usage: %s buildengine [--help] <command> [<args>]\n",
          getProgramName());
  fprintf(stderr, "\n");
  fprintf(stderr, "Available commands:\n");
  fprintf(stderr, "  ack           -- Compute Ackermann\n");
  fprintf(stderr, "  evo           -- Compute Ackermann - Evo Engine\n");
  fprintf(stderr, "\n");
  exit(1);
}

int commands::executeBuildEngineCommand(const std::vector<std::string> &args) {
  // Expect the first argument to be the name of another subtool to delegate to.
  if (args.empty() || args[0] == "--help")
    usage();

  if (args[0] == "ack" || args[0] == "evo") {
    return executeAckermannCommand(args[0], {args.begin()+1, args.end()});
  } else {
    fprintf(stderr, "error: %s: unknown command '%s'\n", getProgramName(),
            args[0].c_str());
    return 1;
  }
}