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, llvm-gcc, and dragonegg as well as run tests
13 # on them. This script is convenient to use to check builds and tests
14 # before committing changes to the upstream repository
16 # A typical source setup uses three trees and looks like this:
70 # "gcc" above is the upstream FSF gcc and "gcc/trunk" refers to the
71 # 4.5 branch as discussed in the dragonegg build guide.
73 # In a typical workflow, the "official" tree always contains unchanged
74 # sources from the main LLVM project repositories. The "staging" tree
75 # is where local work is done. A set of changes resides there waiting
76 # to be moved upstream. The "commit" tree is where changes from
77 # "staging" make their way upstream. Individual incremental changes
78 # from "staging" are applied to "commit" and committed upstream after
79 # a successful build and test run. A successful build is one in which
80 # testing results in no more failures than seen in the testing of the
83 # A build may be invoked as such:
85 # llvmbuild --src=~/llvm/commit --src=~/llvm/staging
86 # --src=~/llvm/official --branch=trunk --branch=tags/RELEASE_28
87 # --build=debug --build=release --build=paranoid
88 # --prefix=/home/greened/install --builddir=/home/greened/build
90 # This will build the LLVM ecosystem, including LLVM, Clang, llvm-gcc,
91 # gcc 4.5 and dragonegg, putting build results in ~/build and
92 # installing tools in ~/install. llvmbuild creates separate build and
93 # install directories for each source/branch/build flavor. In the
94 # above example, llvmbuild will build debug, release and paranoid
95 # (debug+checks) flavors of the trunk and RELEASE_28 branches from
96 # each source tree (official, staging and commit) for a total of
97 # eighteen builds. All builds will be run in parallel.
99 # The user may control parallelism via the --jobs and --threads
100 # switches. --jobs tells llvmbuild the maximum total number of builds
101 # to activate in parallel. The user may think of it as equivalent to
102 # the GNU make -j switch. --threads tells llvmbuild how many worker
103 # threads to use to accomplish those builds. If --threads is less
104 # than --jobs, --threads workers will be launched and each one will
105 # pick a source/branch/flavor combination to build. Then llvmbuild
106 # will invoke GNU make with -j (--jobs / --threads) to use up the
107 # remaining job capacity. Once a worker is finished with a build, it
108 # will pick another combination off the list and start building it.
110 ##===----------------------------------------------------------------------===##
122 # TODO: Use shutil.which when it is available (3.2 or later)
123 def find_executable(executable, path=None):
124 """Try to find 'executable' in the directories listed in 'path' (a
125 string listing directories separated by 'os.pathsep'; defaults to
126 os.environ['PATH']). Returns the complete filename or None if not
130 path = os.environ['PATH']
131 paths = path.split(os.pathsep)
134 (base, ext) = os.path.splitext(executable)
135 # executable files on OS/2 can have an arbitrary extension, but
136 # .exe is automatically appended if no dot is present in the name
138 executable = executable + ".exe"
139 elif sys.platform == 'win32':
140 pathext = os.environ['PATHEXT'].lower().split(os.pathsep)
141 (base, ext) = os.path.splitext(executable)
142 if ext.lower() not in pathext:
145 execname = executable + ext
146 if os.path.isfile(execname):
150 f = os.path.join(p, execname)
151 if os.path.isfile(f):
156 def is_executable(fpath):
157 return os.path.exists(fpath) and os.access(fpath, os.X_OK)
159 def add_options(parser):
160 parser.add_option("-v", "--verbose", action="store_true",
162 help=("Output informational messages"
163 " [default: %default]"))
164 parser.add_option("--src", action="append",
165 help=("Top-level source directory [default: %default]"))
166 parser.add_option("--build", action="append", default=["debug"],
167 help=("Build types to run [default: %default]"))
168 parser.add_option("--branch", action="append",
169 help=("Source branch to build [default: %default]"))
170 parser.add_option("--cc", default=find_executable("cc"),
171 help=("The C compiler to use [default: %default]"))
172 parser.add_option("--cxx", default=find_executable("c++"),
173 help=("The C++ compiler to use [default: %default]"))
174 parser.add_option("--threads", default=4, type="int",
175 help=("The number of worker threads to use "
176 "[default: %default]"))
177 parser.add_option("--jobs", "-j", default=8, type="int",
178 help=("The number of simultaneous build jobs "
179 "[default: %default]"))
180 parser.add_option("--prefix",
181 help=("Root install directory [default: %default]"))
182 parser.add_option("--builddir",
183 help=("Root build directory [default: %default]"))
186 def check_options(parser, options, valid_builds):
187 # See if we're building valid flavors.
188 for build in options.build:
189 if (build not in valid_builds):
190 parser.error("'" + build + "' is not a valid build flavor "
193 # See if we can find source directories.
194 for src in options.src:
195 for component in ["llvm", "llvm-gcc", "gcc", "dragonegg"]:
196 compsrc = src + "/" + component
197 if (not os.path.isdir(compsrc)):
198 parser.error("'" + compsrc + "' does not exist")
199 if (options.branch is not None):
200 for branch in options.branch:
201 if (not os.path.isdir(os.path.join(compsrc, branch))):
202 parser.error("'" + os.path.join(compsrc, branch)
203 + "' does not exist")
205 # See if we can find the compilers
206 options.cc = find_executable(options.cc)
207 options.cxx = find_executable(options.cxx)
211 # Find a unique short name for the given set of paths. This searches
212 # back through path components until it finds unique component names
213 # among all given paths.
214 def get_path_abbrevs(paths):
215 # Find the number of common starting characters in the last component
217 unique_paths = list(paths)
219 class NotFoundException(Exception): pass
221 # Find a unique component of each path.
222 unique_bases = unique_paths[:]
224 while len(unique_paths) > 0:
225 bases = [os.path.basename(src) for src in unique_paths]
226 components = { c for c in bases }
227 # Account for single entry in paths.
228 if len(components) > 1 or len(components) == len(bases):
229 # We found something unique.
231 if bases.count(c) == 1:
232 index = bases.index(c)
233 unique_bases[index] = c
234 # Remove the corresponding path from the set under
236 unique_paths[index] = None
237 unique_paths = [ p for p in unique_paths if p is not None ]
238 unique_paths = [os.path.dirname(src) for src in unique_paths]
240 if len(unique_paths) > 0:
241 raise NotFoundException()
243 abbrevs = dict(zip(paths, [base for base in unique_bases]))
247 # Given a set of unique names, find a short character sequence that
248 # uniquely identifies them.
249 def get_short_abbrevs(unique_bases):
250 # Find a unique start character for each path base.
251 my_unique_bases = unique_bases[:]
252 unique_char_starts = unique_bases[:]
253 while len(my_unique_bases) > 0:
254 for start, char_tuple in enumerate(zip(*[base
255 for base in my_unique_bases])):
256 chars = { c for c in char_tuple }
257 # Account for single path.
258 if len(chars) > 1 or len(chars) == len(char_tuple):
259 # We found something unique.
261 if char_tuple.count(c) == 1:
262 index = char_tuple.index(c)
263 unique_char_starts[index] = start
264 # Remove the corresponding path from the set under
266 my_unique_bases[index] = None
267 my_unique_bases = [ b for b in my_unique_bases
271 if len(my_unique_bases) > 0:
272 raise NotFoundException()
274 abbrevs = [abbrev[start_index:start_index+3]
275 for abbrev, start_index
276 in zip([base for base in unique_bases],
277 [index for index in unique_char_starts])]
279 abbrevs = dict(zip(unique_bases, abbrevs))
283 class Builder(threading.Thread):
284 class ExecutableNotFound(Exception): pass
285 class FileNotExecutable(Exception): pass
287 def __init__(self, work_queue, jobs, cc, cxx, build_abbrev, source_abbrev,
288 branch_abbrev, build_prefix, install_prefix):
290 self.work_queue = work_queue
294 self.build_abbrev = build_abbrev
295 self.source_abbrev = source_abbrev
296 self.branch_abbrev = branch_abbrev
297 self.build_prefix = build_prefix
298 self.install_prefix = install_prefix
299 self.component_abbrev = dict(
308 source, branch, build = self.work_queue.get()
309 self.dobuild(source, branch, build)
311 traceback.print_exc()
313 self.work_queue.task_done()
315 def execute(self, command, execdir, env, component):
316 prefix = self.component_abbrev[component.replace("-", "_")]
318 if not os.path.exists(execdir):
321 for key, value in env.items():
322 os.environ[key] = value
324 self.logger.debug("[" + prefix + "] " + "env " + str(env) + " "
325 + " ".join(command));
328 proc = subprocess.Popen(command,
330 stdout=subprocess.PIPE,
331 stderr=subprocess.STDOUT)
333 line = proc.stdout.readline()
335 self.logger.info("[" + prefix + "] "
336 + str(line, "utf-8").rstrip())
337 line = proc.stdout.readline()
340 traceback.print_exc()
342 for key, value in env.items():
345 # Get a list of C++ include directories to pass to clang.
346 def get_includes(self):
347 # Assume we're building with g++ for now.
349 command += ["-v", "-x", "c++", "/dev/null", "-fsyntax-only"]
351 self.logger.debug(command)
353 proc = subprocess.Popen(command,
354 stdout=subprocess.PIPE,
355 stderr=subprocess.STDOUT)
358 line = proc.stdout.readline()
360 self.logger.debug(line)
361 if re.search("End of search list", str(line)) is not None:
362 self.logger.debug("Stop Gather")
365 includes.append(str(line, "utf-8").strip())
366 if re.search("#include <...> search starts", str(line)) is not None:
367 self.logger.debug("Start Gather")
369 line = proc.stdout.readline()
371 traceback.print_exc()
372 self.logger.debug(includes)
375 def dobuild(self, source, branch, build):
378 ssabbrev = get_short_abbrevs([ab for ab in self.source_abbrev.values()])
380 if branch is not None:
381 sbabbrev = get_short_abbrevs([ab for ab in self.branch_abbrev.values()])
383 prefix = "[" + ssabbrev[self.source_abbrev[source]] + "-" + sbabbrev[self.branch_abbrev[branch]] + "-" + self.build_abbrev[build] + "]"
384 self.install_prefix += "/" + self.source_abbrev[source] + "/" + branch + "/" + build
385 build_suffix += self.source_abbrev[source] + "/" + branch + "/" + build
387 prefix = "[" + ssabbrev[self.source_abbrev[source]] + "-" + self.build_abbrev[build] + "]"
388 self.install_prefix += "/" + self.source_abbrev[source] + "/" + build
389 build_suffix += "/" + self.source_abbrev[source] + "/" + build
391 self.logger = logging.getLogger(prefix)
393 self.logger.debug(self.install_prefix)
395 # Assume we're building with gcc for now.
396 cxxincludes = self.get_includes()
397 cxxroot = cxxincludes[0]
398 cxxarch = os.path.basename(cxxincludes[1])
400 configure_flags = dict(
401 llvm=dict(debug=["--prefix=" + self.install_prefix,
402 "--with-cxx-include-root=" + cxxroot,
403 "--with-cxx-include-arch=" + cxxarch],
404 release=["--prefix=" + self.install_prefix,
405 "--enable-optimized",
406 "--with-cxx-include-root=" + cxxroot,
407 "--with-cxx-include-arch=" + cxxarch],
408 paranoid=["--prefix=" + self.install_prefix,
409 "--enable-expensive-checks",
410 "--with-cxx-include-root=" + cxxroot,
411 "--with-cxx-include-arch=" + cxxarch]),
412 llvm_gcc=dict(debug=["--prefix=" + self.install_prefix,
414 "--program-prefix=llvm-",
415 "--enable-llvm=" + self.build_prefix + "/llvm/" + build_suffix,
416 "--enable-languages=c,c++,fortran"],
417 release=["--prefix=" + self.install_prefix,
418 "--program-prefix=llvm-",
419 "--enable-llvm=" + self.build_prefix + "/llvm/" + build_suffix,
420 "--enable-languages=c,c++,fortran"],
421 paranoid=["--prefix=" + self.install_prefix,
423 "--program-prefix=llvm-",
424 "--enable-llvm=" + self.build_prefix + "/llvm/" + build_suffix,
425 "--enable-languages=c,c++,fortran"]),
426 llvm2=dict(debug=["--prefix=" + self.install_prefix,
427 "--with-llvmgccdir=" + self.install_prefix + "/bin",
428 "--with-cxx-include-root=" + cxxroot,
429 "--with-cxx-include-arch=" + cxxarch],
430 release=["--prefix=" + self.install_prefix,
431 "--enable-optimized",
432 "--with-llvmgccdir=" + self.install_prefix + "/bin",
433 "--with-cxx-include-root=" + cxxroot,
434 "--with-cxx-include-arch=" + cxxarch],
435 paranoid=["--prefix=" + self.install_prefix,
436 "--enable-expensive-checks",
437 "--with-llvmgccdir=" + self.install_prefix + "/bin",
438 "--with-cxx-include-root=" + cxxroot,
439 "--with-cxx-include-arch=" + cxxarch]),
440 gcc=dict(debug=["--prefix=" + self.install_prefix,
441 "--enable-checking"],
442 release=["--prefix=" + self.install_prefix],
443 paranoid=["--prefix=" + self.install_prefix,
444 "--enable-checking"]),
445 dragonegg=dict(debug=[],
449 configure_env = dict(
450 llvm=dict(debug=dict(CC=self.cc,
452 release=dict(CC=self.cc,
454 paranoid=dict(CC=self.cc,
456 llvm_gcc=dict(debug=dict(CC=self.cc,
458 release=dict(CC=self.cc,
460 paranoid=dict(CC=self.cc,
462 llvm2=dict(debug=dict(CC=self.cc,
464 release=dict(CC=self.cc,
466 paranoid=dict(CC=self.cc,
468 gcc=dict(debug=dict(CC=self.cc,
470 release=dict(CC=self.cc,
472 paranoid=dict(CC=self.cc,
474 dragonegg=dict(debug=dict(CC=self.cc,
476 release=dict(CC=self.cc,
478 paranoid=dict(CC=self.cc,
482 llvm=dict(debug=["-j" + str(self.jobs)],
483 release=["-j" + str(self.jobs)],
484 paranoid=["-j" + str(self.jobs)]),
485 llvm_gcc=dict(debug=["-j" + str(self.jobs),
487 release=["-j" + str(self.jobs),
489 paranoid=["-j" + str(self.jobs),
491 llvm2=dict(debug=["-j" + str(self.jobs)],
492 release=["-j" + str(self.jobs)],
493 paranoid=["-j" + str(self.jobs)]),
494 gcc=dict(debug=["-j" + str(self.jobs),
496 release=["-j" + str(self.jobs),
498 paranoid=["-j" + str(self.jobs),
500 dragonegg=dict(debug=["-j" + str(self.jobs)],
501 release=["-j" + str(self.jobs)],
502 paranoid=["-j" + str(self.jobs)]))
505 llvm=dict(debug=dict(),
508 llvm_gcc=dict(debug=dict(),
511 llvm2=dict(debug=dict(),
514 gcc=dict(debug=dict(),
517 dragonegg=dict(debug=dict(GCC=self.install_prefix + "/bin/gcc",
518 LLVM_CONFIG=self.install_prefix + "/bin/llvm-config"),
519 release=dict(GCC=self.install_prefix + "/bin/gcc",
520 LLVM_CONFIG=self.install_prefix + "/bin/llvm-config"),
521 paranoid=dict(GCC=self.install_prefix + "/bin/gcc",
522 LLVM_CONFIG=self.install_prefix + "/bin/llvm-config")))
524 make_install_flags = dict(
525 llvm=dict(debug=["install"],
527 paranoid=["install"]),
528 llvm_gcc=dict(debug=["install"],
530 paranoid=["install"]),
531 llvm2=dict(debug=["install"],
533 paranoid=["install"]),
534 gcc=dict(debug=["install"],
536 paranoid=["install"]),
537 dragonegg=dict(debug=["install"],
539 paranoid=["install"]))
541 make_install_env = dict(
542 llvm=dict(debug=dict(),
545 llvm_gcc=dict(debug=dict(),
548 llvm2=dict(debug=dict(),
551 gcc=dict(debug=dict(),
554 dragonegg=dict(debug=dict(),
558 make_check_flags = dict(
559 llvm=dict(debug=["check"],
562 llvm_gcc=dict(debug=["check"],
565 llvm2=dict(debug=["check"],
568 gcc=dict(debug=["check"],
571 dragonegg=dict(debug=["check"],
575 make_check_env = dict(
576 llvm=dict(debug=dict(),
579 llvm_gcc=dict(debug=dict(),
582 llvm2=dict(debug=dict(),
585 gcc=dict(debug=dict(),
588 dragonegg=dict(debug=dict(),
592 for component in ["llvm", "llvm-gcc", "llvm2", "gcc", "dragonegg"]:
595 srcdir = source + "/" + comp.rstrip("2")
596 builddir = self.build_prefix + "/" + comp + "/" + build_suffix
597 installdir = self.install_prefix
599 if (branch is not None):
600 srcdir += "/" + branch
602 self.logger.info("Configuring " + component + " in " + builddir)
603 self.configure(component, srcdir, builddir,
604 configure_flags[comp.replace("-", "_")][build],
605 configure_env[comp.replace("-", "_")][build])
607 self.logger.info("Building " + component + " in " + builddir)
608 self.make(component, srcdir, builddir,
609 make_flags[comp.replace("-", "_")][build],
610 make_env[comp.replace("-", "_")][build])
612 self.logger.info("Installing " + component + " in " + installdir)
613 self.make(component, srcdir, builddir,
614 make_install_flags[comp.replace("-", "_")][build],
615 make_install_env[comp.replace("-", "_")][build])
617 self.logger.info("Testing " + component + " in " + builddir)
618 self.make(component, srcdir, builddir,
619 make_check_flags[comp.replace("-", "_")][build],
620 make_check_env[comp.replace("-", "_")][build])
623 def configure(self, component, srcdir, builddir, flags, env):
624 configure_files = dict(
625 llvm=[(srcdir + "/configure", builddir + "/Makefile")],
626 llvm_gcc=[(srcdir + "/configure", builddir + "/Makefile"),
627 (srcdir + "/gcc/configure", builddir + "/gcc/Makefile")],
628 llvm2=[(srcdir + "/configure", builddir + "/Makefile")],
629 gcc=[(srcdir + "/configure", builddir + "/Makefile"),
630 (srcdir + "/gcc/configure", builddir + "/gcc/Makefile")],
634 for conf, mf in configure_files[component.replace("-", "_")]:
635 if os.path.exists(conf) and os.path.exists(mf):
636 confstat = os.stat(conf)
637 makestat = os.stat(mf)
638 if confstat.st_mtime > makestat.st_mtime:
648 program = srcdir + "/configure"
649 if not is_executable(program):
653 args += ["--verbose"]
655 self.execute(args, builddir, env, component)
657 def make(self, component, srcdir, builddir, flags, env):
658 program = find_executable("make")
660 raise ExecutableNotFound
662 if not is_executable(program):
663 raise FileNotExecutable
667 self.execute(args, builddir, env, component)
670 build_abbrev = dict(debug="dbg", release="opt", paranoid="par")
673 parser = optparse.OptionParser(version="%prog 1.0")
675 (options, args) = parser.parse_args()
676 check_options(parser, options, build_abbrev.keys());
679 logging.basicConfig(level=logging.DEBUG,
680 format='%(name)-13s: %(message)s')
682 logging.basicConfig(level=logging.INFO,
683 format='%(name)-13s: %(message)s')
685 source_abbrev = get_path_abbrevs(set(options.src))
686 branch_abbrev = get_path_abbrevs(set(options.branch))
688 work_queue = queue.Queue()
690 for t in range(options.threads):
691 jobs = options.jobs // options.threads
692 builder = Builder(work_queue, jobs, options.cc.strip(), options.cxx.strip(),
693 build_abbrev, source_abbrev, branch_abbrev,
694 options.builddir.strip(), options.prefix.strip())
695 builder.daemon = True
698 for build in set(options.build):
699 for source in set(options.src):
700 if options.branch is not None:
701 for branch in set(options.branch):
702 work_queue.put((source, branch, build))
704 work_queue.put((source, None, build))