aboutsummaryrefslogtreecommitdiff
path: root/modules/llvm.py
blob: 953b5136f49210914e5545c53c34e0b7f0c32400 (plain)
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
import os
import re

from functools import partial

from linaropy.git.worktree import Worktree


class LLVMSubproject(object):
    """
    Class that keeps track of everything related to an LLVM subproject (clang,
    lld, compiler-rt etc): repo URL, location preferred by CMake,
    CMake variable for adding or removing it from the build etc.
    """

    def __init__(self, cmake_path, cmake_var):
        """Create an LLVMSubproject with the provided info.

        Parameters
        ----------
        cmake_path
            Path relative to the LLVM source root where this subproject should
            live so that CMake can automatically pick it up during the build.
        cmake_var
            The name of the CMake variable that can be used to enable/disable
            building this subproject.
        """
        self.cmake_path = cmake_path
        self.cmake_var = cmake_var

    def get_cmake_path(self, llvm_source_directory):
        """
        Get the path where this subproject should live in the given LLVM tree so
        that CMake can pick it up by default.
        """
        return os.path.join(llvm_source_directory, self.cmake_path)

    @classmethod
    def get_all_subprojects(cls):
        """
        Return a dictionary of all the LLVM subprojects.
        At the moment, llvm itself is not part of the subprojects, because it
        always needs to be there and everything is relative to it.
        """
        return {
            "clang":
                cls(os.path.join("tools", "clang"), "LLVM_TOOL_CLANG_BUILD"),
            "compiler-rt":
                cls(os.path.join("projects", "compiler-rt"),
                    "LLVM_TOOL_COMPILER_RT_BUILD"),
            "libcxx":
                cls(os.path.join("projects", "libcxx"),
                    "LLVM_TOOL_LIBCXX_BUILD"),
            "libcxxabi":
                cls(os.path.join("projects", "libcxxabi"),
                    "LLVM_TOOL_LIBCXXABI_BUILD"),
            "libunwind":
                cls(os.path.join("projects", "libunwind"),
                    "LLVM_TOOL_LIBUNWIND_BUILD"),
            "lld":
                cls(os.path.join("tools", "lld"), "LLVM_TOOL_LLD_BUILD"),
            "lldb":
                cls(os.path.join("tools", "lldb"), "LLVM_TOOL_LLDB_BUILD"),
            "test-suite":
                cls(os.path.join("projects", "test-suite"), None),
        }


class LLVMSourceConfig(object):
    """Class for managing an LLVM source tree.

    It keeps track of which subprojects are enabled in a given tree and provides
    functionality for adding / removing them.
    """

    def __init__(self, proj, sourcePath, dry,
                 subprojs=LLVMSubproject.get_all_subprojects()):
        """ Create a source configuration.

        Parameters
        ----------
        proj : Proj
            Temporary project directory (used mostly for logging).
        sourcePath
            Must point to a valid LLVM source tree.
        dry
            Whether or not we are running in dry run mode. If we are, then we do
            not try to add or remove any subprojects, but we try to remember
            which updates we performed. We don't currently check the subprojects
            that are enabled on disk, since for the dry run mode we don't
            perform any validation whatsoever on the source directory. This may
            change in the future.
        subprojs : dictionary
            Dictionary containing a number of LLVMSubproject objects.
            By default, this contains all the LLVM subprojects as returned by
            LLVMSubproject.get_all_subprojects(), but any subset would work just
            as well.
            The keys will be used to identify the subprojects in any of this
            class's methods. It is an error to invoke them with a subproj that
            does not exist in this dictionary.
        """
        if not dry:
            sourcePath = str(sourcePath)
            if not os.path.isdir(sourcePath):
                raise EnvironmentError("Invalid path to LLVM source tree")
            self.proj = proj
            self.llvmSourceTree = Worktree(proj, sourcePath)
        else:
            self.subprojsEnabledInDryRun = []

        self.sourcePath = sourcePath
        self.dry = dry
        self.subprojs = subprojs

    def get_path(self):
        """Get the path corresponding to this source config."""
        return self.sourcePath

    def get_enabled_subprojects(self):
        """Get a list of the subprojects enabled in this configuration."""
        enabled = []
        for subproj in self.subprojs:
            if self.__is_enabled(subproj):
                enabled.append(subproj)
        return enabled

    def update(self, add={}, remove=[]):
        """Update the configuration by adding/removing subprojects.

        Parameters
        ----------
        add : dictionary
            A map of (subproject name, repo) to add to the config. The order in
            which the subprojects are added is unspecified. Subprojects that are
            already enabled in the config are ignored.
        remove: list
            A list of subproject names to remove from the config. The order in
            which the subprojects are removed is unspecified. Duplicates and
            subprojects that aren't enabled in the config are ignored. A
            subproject may be removed even if it is in an invalid state.

        For both add and remove, the subproject name must exist in the
        dictionary that the config was initialized with and the repo must be a
        valid GitRepo object.

        TODO: If adding/removing a project fails, this function should try to
        recover.
        """

        # Make the inputs friendly
        if add is None:
            add = {}

        if remove is None:
            remove = []

        for subproj in list(add.keys()):
            if subproj in remove:
                raise ValueError("Can't add and remove {} at the same time"
                                 .format(subproj))

        for (subproj, repo) in list(add.items()):
            self.__add_subproject(subproj, repo)

        for subproj in remove:
            self.__remove_subproject(subproj)

    def for_each_enabled(self, action):
        """Perform the given action for each enabled subproject including LLVM.

        The action must be a callable object receiving the path to the
        subproject's directory as its only parameter.

        If the action throws an exception, it will be rethrown as a
        RuntimeError. Note that this does not have transactional behaviour.
        """
        for subproj in self.get_enabled_subprojects():
            try:
                action(self.__get_subproj_cmake_path(subproj))
            except Exception as exc:
                raise RuntimeError("Error while processing {}".format(subproj)) from exc

        # Visit LLVM last, in case getting the enabled subprojects errors out.
        action(self.sourcePath)

    def for_each_subproj(self, action):
        """Perform the given action for each subproject excluding LLVM.

        The action must be a callable object receiving an LLVMSubproject
        parameter and a boolean representing whether the subproject is enabled
        in the current configuration or not.

        If the action throws an exception, it will be rethrown as a
        RuntimeError. Note that this does not have transactional behaviour.
        """
        for subprojName, subproj in self.subprojs.items():
            try:
                action(subproj, self.__is_enabled(subprojName))
            except Exception as exc:
                raise RuntimeError("Error while processing {}".format(subprojName)) from exc

    def __get_subproj_object(self, subprojName):
        """Get the LLVMSubproject object corresponding to subprojName."""
        if not subprojName in list(self.subprojs.keys()):
            raise ValueError("Unknown llvm subproject {0}".format(subprojName))
        return self.subprojs[subprojName]

    def __get_subproj_cmake_path(self, subprojName):
        """Get the full path to subprojName in this source tree."""
        subproj = self.__get_subproj_object(subprojName)
        return subproj.get_cmake_path(self.sourcePath)

    def __is_enabled(self, subprojName):
        """
        Check if subproj is enabled in this configuration. A subproj is
        considered to be enabled if it is a worktree on the correct branch. If
        a directory for the subproject exists but does not satisfy those
        conditions, an EnvironmentError is thrown.
        """
        if self.dry:
            return subprojName in self.subprojsEnabledInDryRun

        subprojPath = self.__get_subproj_cmake_path(subprojName)

        if not os.path.isdir(subprojPath):
            return False

        existing = Worktree(self.proj, subprojPath)

        if existing.getbranch() != self.llvmSourceTree.getbranch():
            raise EnvironmentError("{} is on branch {}, but should be on {}".format(
                subprojName, existing.getbranch(), self.llvmSourceTree.getbranch()))

        return True

    # TODO: add_subproject, remove_subproject and is_enabled should live in
    # another object (AddRemoveStrategy?) that would know what we want to add
    # (worktrees, links, whatever)
    def __add_subproject(self, subprojName, subprojRepo):
        """Add a given subproject to this configuration.

        This will make sure the subproject's sources are visible in the proper
        place in the LLVM source tree that the configuration was created with.

        We currently achieve this by creating a worktree for the subproject, but
        if more flexibility is needed we can add a config option. The branch
        that the worktree will be created with is the same branch that the
        existing LLVM source tree is on, and it will be tracking a branch
        corresponding to the one that the LLVM branch was forked from.
        """
        path = self.__get_subproj_cmake_path(subprojName)

        if self.__is_enabled(subprojName):
            # Subproject has already been added, nothing to do.
            return

        if self.dry:
            self.subprojsEnabledInDryRun.append(subprojName)
            return

        if os.path.exists(path):
            raise EnvironmentError(
                "{} already exists but is not a valid subproject directory."
                    .format(path) +
                "Please make sure it is a worktree on the same branch as LLVM.")

        # Create a new worktree
        branch = self.llvmSourceTree.getbranch()
        if subprojRepo.branch_exists(branch):
            Worktree.create(self.proj, subprojRepo, path, branch)
        else:
            trackedBranch = "master"  # TODO: track proper branch
            Worktree.create(
                self.proj,
                subprojRepo,
                path,
                branch,
                trackedBranch)

    def __remove_subproject(self, subprojName):
        """Remove a given subproject from this build configuration."""
        if self.dry:
            if self.__is_enabled(subprojName):
                self.subprojsEnabledInDryRun.remove(subprojName)
            return

        path = self.__get_subproj_cmake_path(subprojName)

        if not os.path.isdir(path):
            return

        worktree = Worktree(self.proj, path)
        worktree.clean(False)


class LLVMBuildConfig(object):
    """Class for managing an LLVM build directory.

    It should know how to configure a build directory (with CMake) and how to
    run a build command. The directory must already exist, but it may be empty.
    """

    def __init__(self, sourceConfig, buildDir=None):
        """Create an LLVMBuildConfig."""
        self.sourceConfig = sourceConfig
        self.buildDir = buildDir

    def cmake(self, commandConsumer, cmakeFlags, generator):
        """
        Generate the CMake command needed for configuring the build directory
        with the given flags and generator, and pass it to the 'commandConsumer'.

        The command will always explicitly enable or disable the build of
        specific subprojects to mirror the source config. This is important
        because projects can always be added or removed from the source config,
        and CMake doesn't by default pick up the new situation (so we might end
        up trying to build subprojects that were removed, or not build
        subprojects that were added).

        The 'commandConsumer' should have a 'consume' method taking two
        parameters: the command to be consumed (in the form of a list) and the
        directory where the command should be run. Any exceptions that may be
        raised by that method should be handled by the calling code.
        """
        cmakeSubprojFlags = self.__get_subproj_flags()
        command = ["cmake", "-G", generator] + cmakeSubprojFlags + \
            cmakeFlags + [self.sourceConfig.get_path()]
        commandConsumer.consume(command, self.buildDir)

    def __get_subproj_flags(self):
        """
        Get the CMake flags needed to explicitly enable or disable the build of
        each specific subproject, depending on whether it is enabled or disabled
        in the source config.
        """
        def append_cmake_var(cmakeVars, subproj, enabled):
            if subproj.cmake_var is None:
                return

            if enabled:
                status = "ON"
            else:
                status = "OFF"
            cmakeVars.append("-D{}={}".format(subproj.cmake_var, status))

        cmakeSubprojFlags = []
        self.sourceConfig.for_each_subproj(partial(append_cmake_var,
                                                   cmakeSubprojFlags))

        return cmakeSubprojFlags


def build_llvm(commandConsumer, buildDir, flags=[]):
    """
    Generate a build command and pass it to the 'commandConsumer'.

    The build command that is generated will depend on what 'buildDir' contains.
    If it contains a 'build.ninja', a 'ninja' command will be generated.
    Otherwise, if it contains a 'Makefile', a 'make' command will be generated.
    Otherwise, a RuntimeError will be thrown.

    The 'commandConsumer' should have a 'consume' method taking two parameters:
    the command to be consumed (in the form of a list) and the directory where
    the command should be run. Any exceptions that may be raised by that method
    should be handled by the calling code.

    The 'buildDir' needs to be the path to an already-configured build
    directory.

    The 'flags' should be a list of flags to be passed to the build command,
    e.g. ["-j8", "llvm-check-codegen-aarch64"].
    """
    useNinja = os.path.exists(os.path.join(buildDir, 'build.ninja'))
    useMake = os.path.exists(os.path.join(buildDir, 'Makefile'))

    if useNinja:
        buildTool = "ninja"
    elif useMake:
        buildTool = "make"
    else:
        raise RuntimeError(
            "Couldn't identify build system to use for {}. "
            "It does not contain 'build.ninja' or 'Makefile'. "
            "Are you sure it was configured?".format(buildDir))

    command = [buildTool] + flags
    commandConsumer.consume(command, buildDir)


def setup_test_suite(commandConsumer, sandbox, lnt):
    """
    Generate the commands needed for setting up a sandbox for running the
    test-suite and pass them to the 'commandConsumer'.

    The 'commandConsumer' should have a 'consume' method taking two
    parameters: the command to be consumed (in the form of a list) and the
    directory where the command should be run. Any exceptions that may be
    raised by that method should be handled by the calling code.

    The 'sandbox' should be the path where we want to set things up (it will be
    created if it doesn't exist) and 'lnt' should be the path to the LNT source
    tree.
    """
    # These commands don't need to run in any particular directory, just use the
    # current working directory.
    commandConsumer.consume(["virtualenv", sandbox], None)
    commandConsumer.consume(["{}/bin/python".format(sandbox),
                             "{}/setup.py".format(lnt), "develop"], None)


def run_test_suite(commandConsumer, sandbox, testsuite, lit, flags=[]):
    """
    Generate the command needed for running the test-suite with the given
    parameters and pass it to the 'commandConsumer'.

    The 'commandConsumer' should have a 'consume' method taking two
    parameters: the command to be consumed (in the form of a list) and the
    directory where the command should be run. Any exceptions that may be
    raised by that method should be handled by the calling code.

    The 'sandbox' should be the path to an already-setup virtualenv for running
    the test-suite. The 'testsuite' and 'lit' should be the paths to the
    test-suite repository and to the 'llvm-lit' binary (usually found in the
    LLVM build directory under 'bin'), respectively.
    """

    python = os.path.join(sandbox, "bin", "python")
    lnt = os.path.join(sandbox, "bin", "lnt")

    command = [python, lnt, "runtest", "test-suite",
               "--sandbox={}".format(sandbox),
               "--test-suite={}".format(testsuite),
               "--use-lit={}".format(lit)] + flags

    # This doesn't need to run in any particular directory, just use the current
    # working directory.
    commandConsumer.consume(command, None)