2 ##===- utils/llvmbuild - Build the LLVM project ----------------*-python-*-===##
4 # The LLVM Compiler Infrastructure
6 # This file is distributed under the University of Illinois Open Source
7 # License. See LICENSE.TXT for details.
9 ##===----------------------------------------------------------------------===##
11 # This script builds many different flavors of the LLVM ecosystem. It
12 # will build LLVM, Clang and dragonegg as well as run tests on them.
13 # This script is convenient to use to check builds and tests before
14 # committing changes to the upstream repository
16 # A typical source setup uses three trees and looks like this:
34 # In a typical workflow, the "official" tree always contains unchanged
35 # sources from the main LLVM project repositories. The "staging" tree
36 # is where local work is done. A set of changes resides there waiting
37 # to be moved upstream. The "commit" tree is where changes from
38 # "staging" make their way upstream. Individual incremental changes
39 # from "staging" are applied to "commit" and committed upstream after
40 # a successful build and test run. A successful build is one in which
41 # testing results in no more failures than seen in the testing of the
44 # A build may be invoked as such:
46 # llvmbuild --src=~/llvm/commit --src=~/llvm/staging --src=~/llvm/official
47 # --build=debug --build=release --build=paranoid
48 # --prefix=/home/greened/install --builddir=/home/greened/build
50 # This will build the LLVM ecosystem, including LLVM, Clangand
51 # dragonegg, putting build results in ~/build and installing tools in
52 # ~/install. llvm-compilers-check creates separate build and install
53 # directories for each source/build flavor. In the above example,
54 # llvmbuild will build debug, release and paranoid (debug+checks)
55 # flavors from each source tree (official, staging and commit) for a
56 # total of nine builds. All builds will be run in parallel.
58 # The user may control parallelism via the --jobs and --threads
59 # switches. --jobs tells llvm-compilers-checl the maximum total
60 # number of builds to activate in parallel. The user may think of it
61 # as equivalent to the GNU make -j switch. --threads tells
62 # llvm-compilers-check how many worker threads to use to accomplish
63 # those builds. If --threads is less than --jobs, --threads workers
64 # will be launched and each one will pick a source/flavor combination
65 # to build. Then llvm-compilers-check will invoke GNU make with -j
66 # (--jobs / --threads) to use up the remaining job capacity. Once a
67 # worker is finished with a build, it will pick another combination
68 # off the list and start building it.
70 ##===----------------------------------------------------------------------===##
82 # TODO: Use shutil.which when it is available (3.2 or later)
83 def find_executable(executable, path=None):
84 """Try to find 'executable' in the directories listed in 'path' (a
85 string listing directories separated by 'os.pathsep'; defaults to
86 os.environ['PATH']). Returns the complete filename or None if not
90 path = os.environ['PATH']
91 paths = path.split(os.pathsep)
94 (base, ext) = os.path.splitext(executable)
95 # executable files on OS/2 can have an arbitrary extension, but
96 # .exe is automatically appended if no dot is present in the name
98 executable = executable + ".exe"
99 elif sys.platform == 'win32':
100 pathext = os.environ['PATHEXT'].lower().split(os.pathsep)
101 (base, ext) = os.path.splitext(executable)
102 if ext.lower() not in pathext:
105 execname = executable + ext
106 if os.path.isfile(execname):
110 f = os.path.join(p, execname)
111 if os.path.isfile(f):
116 def is_executable(fpath):
117 return os.path.exists(fpath) and os.access(fpath, os.X_OK)
119 def add_options(parser):
120 parser.add_option("-v", "--verbose", action="store_true",
122 help=("Output informational messages"
123 " [default: %default]"))
124 parser.add_option("--src", action="append",
125 help=("Top-level source directory [default: %default]"))
126 parser.add_option("--build", action="append",
127 help=("Build types to run [default: %default]"))
128 parser.add_option("--cc", default=find_executable("cc"),
129 help=("The C compiler to use [default: %default]"))
130 parser.add_option("--cxx", default=find_executable("c++"),
131 help=("The C++ compiler to use [default: %default]"))
132 parser.add_option("--threads", default=4, type="int",
133 help=("The number of worker threads to use "
134 "[default: %default]"))
135 parser.add_option("--jobs", "-j", default=8, type="int",
136 help=("The number of simultaneous build jobs "
137 "[default: %default]"))
138 parser.add_option("--prefix",
139 help=("Root install directory [default: %default]"))
140 parser.add_option("--builddir",
141 help=("Root build directory [default: %default]"))
142 parser.add_option("--extra-llvm-config-flags", default="",
143 help=("Extra flags to pass to llvm configure [default: %default]"))
144 parser.add_option("--force-configure", default=False, action="store_true",
145 help=("Force reconfigure of all components"))
146 parser.add_option("--no-dragonegg", default=False, action="store_true",
147 help=("Do not build dragonegg"))
148 parser.add_option("--no-install", default=False, action="store_true",
149 help=("Do not do installs"))
150 parser.add_option("--keep-going", default=False, action="store_true",
151 help=("Keep going after failures"))
152 parser.add_option("--enable-werror", default=False, action="store_true",
153 help=("Build with -Werror"))
156 def check_options(parser, options, valid_builds):
157 # See if we're building valid flavors.
158 for build in options.build:
159 if (build not in valid_builds):
160 parser.error("'" + build + "' is not a valid build flavor "
163 # See if we can find source directories.
164 for src in options.src:
165 for component in components:
166 component = component.rstrip("2")
167 compsrc = src + "/" + component
168 if (not os.path.isdir(compsrc)):
169 parser.error("'" + compsrc + "' does not exist")
171 # See if we can find the compilers
172 options.cc = find_executable(options.cc)
173 options.cxx = find_executable(options.cxx)
177 # Find a unique short name for the given set of paths. This searches
178 # back through path components until it finds unique component names
179 # among all given paths.
180 def get_path_abbrevs(paths):
181 # Find the number of common starting characters in the last component
183 unique_paths = list(paths)
185 class NotFoundException(Exception): pass
187 # Find a unique component of each path.
188 unique_bases = unique_paths[:]
190 while len(unique_paths) > 0:
191 bases = [os.path.basename(src) for src in unique_paths]
192 components = { c for c in bases }
193 # Account for single entry in paths.
194 if len(components) > 1 or len(components) == len(bases):
195 # We found something unique.
197 if bases.count(c) == 1:
198 index = bases.index(c)
199 unique_bases[index] = c
200 # Remove the corresponding path from the set under
202 unique_paths[index] = None
203 unique_paths = [ p for p in unique_paths if p is not None ]
204 unique_paths = [os.path.dirname(src) for src in unique_paths]
206 if len(unique_paths) > 0:
207 raise NotFoundException()
209 abbrevs = dict(zip(paths, [base for base in unique_bases]))
213 # Given a set of unique names, find a short character sequence that
214 # uniquely identifies them.
215 def get_short_abbrevs(unique_bases):
216 # Find a unique start character for each path base.
217 my_unique_bases = unique_bases[:]
218 unique_char_starts = unique_bases[:]
219 while len(my_unique_bases) > 0:
220 for start, char_tuple in enumerate(zip(*[base
221 for base in my_unique_bases])):
222 chars = { c for c in char_tuple }
223 # Account for single path.
224 if len(chars) > 1 or len(chars) == len(char_tuple):
225 # We found something unique.
227 if char_tuple.count(c) == 1:
228 index = char_tuple.index(c)
229 unique_char_starts[index] = start
230 # Remove the corresponding path from the set under
232 my_unique_bases[index] = None
233 my_unique_bases = [ b for b in my_unique_bases
237 if len(my_unique_bases) > 0:
238 raise NotFoundException()
240 abbrevs = [abbrev[start_index:start_index+3]
241 for abbrev, start_index
242 in zip([base for base in unique_bases],
243 [index for index in unique_char_starts])]
245 abbrevs = dict(zip(unique_bases, abbrevs))
249 class Builder(threading.Thread):
250 class ExecutableNotFound(Exception): pass
251 class FileNotExecutable(Exception): pass
253 def __init__(self, work_queue, jobs,
254 build_abbrev, source_abbrev,
257 self.work_queue = work_queue
260 self.cxx = options.cxx
261 self.build_abbrev = build_abbrev
262 self.source_abbrev = source_abbrev
263 self.build_prefix = options.builddir
264 self.install_prefix = options.prefix
265 self.options = options
266 self.component_abbrev = dict(
272 source, build = self.work_queue.get()
273 self.dobuild(source, build)
275 traceback.print_exc()
277 self.work_queue.task_done()
279 def execute(self, command, execdir, env, component):
280 prefix = self.component_abbrev[component.replace("-", "_")]
282 if not os.path.exists(execdir):
285 execenv = os.environ.copy()
287 for key, value in env.items():
290 self.logger.debug("[" + prefix + "] " + "env " + str(env) + " "
291 + " ".join(command));
294 proc = subprocess.Popen(command,
297 stdout=subprocess.PIPE,
298 stderr=subprocess.STDOUT)
300 line = proc.stdout.readline()
302 self.logger.info("[" + prefix + "] "
303 + str(line, "utf-8").rstrip())
304 line = proc.stdout.readline()
306 (stdoutdata, stderrdata) = proc.communicate()
307 retcode = proc.wait()
312 traceback.print_exc()
314 # Get a list of C++ include directories to pass to clang.
315 def get_includes(self):
316 # Assume we're building with g++ for now.
318 command += ["-v", "-x", "c++", "/dev/null", "-fsyntax-only"]
320 self.logger.debug(command)
322 proc = subprocess.Popen(command,
323 stdout=subprocess.PIPE,
324 stderr=subprocess.STDOUT)
327 line = proc.stdout.readline()
329 self.logger.debug(line)
330 if re.search("End of search list", str(line)) is not None:
331 self.logger.debug("Stop Gather")
334 includes.append(str(line, "utf-8").strip())
335 if re.search("#include <...> search starts", str(line)) is not None:
336 self.logger.debug("Start Gather")
338 line = proc.stdout.readline()
341 traceback.print_exc()
342 self.logger.debug(includes)
345 def dobuild(self, source, build):
348 ssabbrev = get_short_abbrevs([ab for ab in self.source_abbrev.values()])
350 prefix = "[" + ssabbrev[self.source_abbrev[source]] + "-" + self.build_abbrev[build] + "]"
351 self.install_prefix += "/" + self.source_abbrev[source] + "/" + build
352 build_suffix += "/" + self.source_abbrev[source] + "/" + build
354 self.logger = logging.getLogger(prefix)
356 self.logger.debug(self.install_prefix)
358 # Assume we're building with gcc for now.
359 cxxincludes = self.get_includes()
360 cxxroot = os.path.dirname(cxxincludes[0]) # Remove the version
361 cxxroot = os.path.dirname(cxxroot) # Remove the c++
362 cxxroot = os.path.dirname(cxxroot) # Remove the include
364 configure_flags = dict(
365 llvm=dict(debug=["--prefix=" + self.install_prefix,
366 "--enable-assertions",
367 "--disable-optimized",
368 "--with-gcc-toolchain=" + cxxroot],
369 release=["--prefix=" + self.install_prefix,
370 "--enable-optimized",
371 "--with-gcc-toolchain=" + cxxroot],
372 paranoid=["--prefix=" + self.install_prefix,
373 "--enable-assertions",
374 "--enable-expensive-checks",
375 "--disable-optimized",
376 "--with-gcc-toolchain=" + cxxroot]),
377 dragonegg=dict(debug=[],
381 if (self.options.enable_werror):
382 configure_flags["llvm"]["debug"].append("--enable-werror")
383 configure_flags["llvm"]["release"].append("--enable-werror")
384 configure_flags["llvm"]["paranoid"].append("--enable-werror")
386 configure_env = dict(
387 llvm=dict(debug=dict(CC=self.cc,
389 release=dict(CC=self.cc,
391 paranoid=dict(CC=self.cc,
393 dragonegg=dict(debug=dict(CC=self.cc,
395 release=dict(CC=self.cc,
397 paranoid=dict(CC=self.cc,
401 llvm=dict(debug=["-j" + str(self.jobs)],
402 release=["-j" + str(self.jobs)],
403 paranoid=["-j" + str(self.jobs)]),
404 dragonegg=dict(debug=["-j" + str(self.jobs)],
405 release=["-j" + str(self.jobs)],
406 paranoid=["-j" + str(self.jobs)]))
409 llvm=dict(debug=dict(),
412 dragonegg=dict(debug=dict(GCC=self.cc,
413 LLVM_CONFIG=self.install_prefix + "/bin/llvm-config"),
414 release=dict(GCC=self.cc,
415 LLVM_CONFIG=self.install_prefix + "/bin/llvm-config"),
416 paranoid=dict(GCC=self.cc,
417 LLVM_CONFIG=self.install_prefix + "/bin/llvm-config")))
419 make_install_flags = dict(
420 llvm=dict(debug=["install"],
422 paranoid=["install"]),
423 dragonegg=dict(debug=["install"],
425 paranoid=["install"]))
427 make_install_env = dict(
428 llvm=dict(debug=dict(),
431 dragonegg=dict(debug=dict(),
435 make_check_flags = dict(
436 llvm=dict(debug=["check"],
439 dragonegg=dict(debug=["check"],
443 make_check_env = dict(
444 llvm=dict(debug=dict(),
447 dragonegg=dict(debug=dict(),
451 for component in components:
454 if (self.options.no_dragonegg):
455 if (comp == 'dragonegg'):
456 self.logger.info("Skipping " + component + " in "
460 srcdir = source + "/" + comp.rstrip("2")
461 builddir = self.build_prefix + "/" + comp + "/" + build_suffix
462 installdir = self.install_prefix
464 comp_key = comp.replace("-", "_")
466 config_args = configure_flags[comp_key][build][:]
467 config_args.extend(getattr(self.options,
468 "extra_" + comp_key.rstrip("2")
472 self.logger.info("Configuring " + component + " in " + builddir)
473 configrc = self.configure(component, srcdir, builddir,
475 configure_env[comp_key][build])
477 if (configrc == None) :
478 self.logger.info("[None] Failed to configure " + component + " in " + installdir)
480 if (configrc == 0 or self.options.keep_going) :
481 self.logger.info("Building " + component + " in " + builddir)
482 self.logger.info("Build: make " + str(make_flags[comp_key][build]))
483 buildrc = self.make(component, srcdir, builddir,
484 make_flags[comp_key][build],
485 make_env[comp_key][build])
487 if (buildrc == None) :
488 self.logger.info("[None] Failed to build " + component + " in " + installdir)
490 if (buildrc == 0 or self.options.keep_going) :
491 self.logger.info("Testing " + component + " in " + builddir)
492 self.logger.info("Test: make "
493 + str(make_check_flags[comp_key][build]))
494 testrc = self.make(component, srcdir, builddir,
495 make_check_flags[comp_key][build],
496 make_check_env[comp_key][build])
498 if (testrc == None) :
499 self.logger.info("[None] Failed to test " + component + " in " + installdir)
501 if ((testrc == 0 or self.options.keep_going)
502 and not self.options.no_install):
503 self.logger.info("Installing " + component + " in " + installdir)
504 self.make(component, srcdir, builddir,
505 make_install_flags[comp_key][build],
506 make_install_env[comp_key][build])
508 self.logger.info("Failed testing " + component + " in " + installdir)
511 self.logger.info("Failed to build " + component + " in " + installdir)
514 self.logger.info("Failed to configure " + component + " in " + installdir)
516 def configure(self, component, srcdir, builddir, flags, env):
517 prefix = self.component_abbrev[component.replace("-", "_")]
519 self.logger.debug("Configure " + str(flags) + " " + str(srcdir) + " -> "
522 configure_files = dict(
523 llvm=[(srcdir + "/configure", builddir + "/Makefile")],
524 dragonegg=[(None,None)])
528 for conf, mf in configure_files[component.replace("-", "_")]:
530 # No configure necessary
533 if not os.path.exists(conf):
534 self.logger.info("[" + prefix + "] Configure failed, no configure script " + conf)
537 if not os.path.exists(mf):
538 self.logger.info("[" + prefix + "] Configure failed, no makefile " + mf)
541 if os.path.exists(conf) and os.path.exists(mf):
542 confstat = os.stat(conf)
543 makestat = os.stat(mf)
544 if confstat.st_mtime > makestat.st_mtime:
551 if not doconfig and not self.options.force_configure:
554 program = srcdir + "/configure"
555 if not is_executable(program):
556 self.logger.info("[" + prefix + "] Configure failed, cannot execute " + program)
560 args += ["--verbose"]
562 return self.execute(args, builddir, env, component)
564 def make(self, component, srcdir, builddir, flags, env):
565 program = find_executable("make")
567 raise ExecutableNotFound
569 if not is_executable(program):
570 raise FileNotExecutable
574 return self.execute(args, builddir, env, component)
577 build_abbrev = dict(debug="dbg", release="opt", paranoid="par")
578 components = ["llvm", "dragonegg"]
581 parser = optparse.OptionParser(version="%prog 1.0")
583 (options, args) = parser.parse_args()
584 check_options(parser, options, build_abbrev.keys());
587 logging.basicConfig(level=logging.DEBUG,
588 format='%(name)-13s: %(message)s')
590 logging.basicConfig(level=logging.INFO,
591 format='%(name)-13s: %(message)s')
593 source_abbrev = get_path_abbrevs(set(options.src))
595 work_queue = queue.Queue()
597 jobs = options.jobs // options.threads
601 numthreads = options.threads
603 logging.getLogger().info("Building with " + str(options.jobs) + " jobs and "
604 + str(numthreads) + " threads using " + str(jobs)
607 logging.getLogger().info("CC = " + str(options.cc))
608 logging.getLogger().info("CXX = " + str(options.cxx))
610 for t in range(numthreads):
611 builder = Builder(work_queue, jobs,
612 build_abbrev, source_abbrev,
614 builder.daemon = True
617 for build in set(options.build):
618 for source in set(options.src):
619 work_queue.put((source, build))