Make IntelJITEvents and OProfileJIT as optional libraries and add
[oota-llvm.git] / utils / llvm-build / llvmbuild / main.py
1 import StringIO
2 import os
3 import sys
4
5 import componentinfo
6 import configutil
7
8 from util import *
9
10 ###
11
12 def cmake_quote_string(value):
13     """
14     cmake_quote_string(value) -> str
15
16     Return a quoted form of the given value that is suitable for use in CMake
17     language files.
18     """
19
20     # Currently, we only handle escaping backslashes.
21     value = value.replace("\\", "\\\\")
22
23     return value
24
25 def cmake_quote_path(value):
26     """
27     cmake_quote_path(value) -> str
28
29     Return a quoted form of the given value that is suitable for use in CMake
30     language files.
31     """
32
33     # CMake has a bug in it's Makefile generator that doesn't properly quote
34     # strings it generates. So instead of using proper quoting, we just use "/"
35     # style paths.  Currently, we only handle escaping backslashes.
36     value = value.replace("\\", "/")
37
38     return value
39
40 def mk_quote_string_for_target(value):
41     """
42     mk_quote_string_for_target(target_name) -> str
43
44     Return a quoted form of the given target_name suitable for including in a 
45     Makefile as a target name.
46     """
47
48     # The only quoting we currently perform is for ':', to support msys users.
49     return value.replace(":", "\\:")
50
51 def make_install_dir(path):
52     """
53     make_install_dir(path) -> None
54
55     Create the given directory path for installation, including any parents.
56     """
57
58     # os.makedirs considers it an error to be called with an existant path.
59     if not os.path.exists(path):
60         os.makedirs(path)
61
62 ###
63
64 class LLVMProjectInfo(object):
65     @staticmethod
66     def load_infos_from_path(llvmbuild_source_root):
67         def recurse(subpath):
68             # Load the LLVMBuild file.
69             llvmbuild_path = os.path.join(llvmbuild_source_root + subpath,
70                                           'LLVMBuild.txt')
71             if not os.path.exists(llvmbuild_path):
72                 fatal("missing LLVMBuild.txt file at: %r" % (llvmbuild_path,))
73
74             # Parse the components from it.
75             common,info_iter = componentinfo.load_from_path(llvmbuild_path,
76                                                             subpath)
77             for info in info_iter:
78                 yield info
79
80             # Recurse into the specified subdirectories.
81             for subdir in common.get_list("subdirectories"):
82                 for item in recurse(os.path.join(subpath, subdir)):
83                     yield item
84
85         return recurse("/")
86
87     @staticmethod
88     def load_from_path(source_root, llvmbuild_source_root):
89         infos = list(
90             LLVMProjectInfo.load_infos_from_path(llvmbuild_source_root))
91
92         return LLVMProjectInfo(source_root, infos)
93
94     def __init__(self, source_root, component_infos):
95         # Store our simple ivars.
96         self.source_root = source_root
97         self.component_infos = list(component_infos)
98         self.component_info_map = None
99         self.ordered_component_infos = None
100
101     def validate_components(self):
102         """validate_components() -> None
103
104         Validate that the project components are well-defined. Among other
105         things, this checks that:
106           - Components have valid references.
107           - Components references do not form cycles.
108
109         We also construct the map from component names to info, and the
110         topological ordering of components.
111         """
112
113         # Create the component info map and validate that component names are
114         # unique.
115         self.component_info_map = {}
116         for ci in self.component_infos:
117             existing = self.component_info_map.get(ci.name)
118             if existing is not None:
119                 # We found a duplicate component name, report it and error out.
120                 fatal("found duplicate component %r (at %r and %r)" % (
121                         ci.name, ci.subpath, existing.subpath))
122             self.component_info_map[ci.name] = ci
123
124         # Disallow 'all' as a component name, which is a special case.
125         if 'all' in self.component_info_map:
126             fatal("project is not allowed to define 'all' component")
127
128         # Add the root component.
129         if '$ROOT' in self.component_info_map:
130             fatal("project is not allowed to define $ROOT component")
131         self.component_info_map['$ROOT'] = componentinfo.GroupComponentInfo(
132             '/', '$ROOT', None)
133         self.component_infos.append(self.component_info_map['$ROOT'])
134
135         # Topologically order the component information according to their
136         # component references.
137         def visit_component_info(ci, current_stack, current_set):
138             # Check for a cycles.
139             if ci in current_set:
140                 # We found a cycle, report it and error out.
141                 cycle_description = ' -> '.join(
142                     '%r (%s)' % (ci.name, relation)
143                     for relation,ci in current_stack)
144                 fatal("found cycle to %r after following: %s -> %s" % (
145                         ci.name, cycle_description, ci.name))
146
147             # If we have already visited this item, we are done.
148             if ci not in components_to_visit:
149                 return
150
151             # Otherwise, mark the component info as visited and traverse.
152             components_to_visit.remove(ci)
153
154             # Validate the parent reference, which we treat specially.
155             if ci.parent is not None:
156                 parent = self.component_info_map.get(ci.parent)
157                 if parent is None:
158                     fatal("component %r has invalid reference %r (via %r)" % (
159                             ci.name, ci.parent, 'parent'))
160                 ci.set_parent_instance(parent)
161
162             for relation,referent_name in ci.get_component_references():
163                 # Validate that the reference is ok.
164                 referent = self.component_info_map.get(referent_name)
165                 if referent is None:
166                     fatal("component %r has invalid reference %r (via %r)" % (
167                             ci.name, referent_name, relation))
168
169                 # Visit the reference.
170                 current_stack.append((relation,ci))
171                 current_set.add(ci)
172                 visit_component_info(referent, current_stack, current_set)
173                 current_set.remove(ci)
174                 current_stack.pop()
175
176             # Finally, add the component info to the ordered list.
177             self.ordered_component_infos.append(ci)
178
179         # FIXME: We aren't actually correctly checking for cycles along the
180         # parent edges. Haven't decided how I want to handle this -- I thought
181         # about only checking cycles by relation type. If we do that, it falls
182         # out easily. If we don't, we should special case the check.
183
184         self.ordered_component_infos = []
185         components_to_visit = set(self.component_infos)
186         while components_to_visit:
187             visit_component_info(iter(components_to_visit).next(), [], set())
188
189         # Canonicalize children lists.
190         for c in self.ordered_component_infos:
191             c.children.sort(key = lambda c: c.name)
192
193     def print_tree(self):
194         def visit(node, depth = 0):
195             print '%s%-40s (%s)' % ('  '*depth, node.name, node.type_name)
196             for c in node.children:
197                 visit(c, depth + 1)
198         visit(self.component_info_map['$ROOT'])
199
200     def write_components(self, output_path):
201         # Organize all the components by the directory their LLVMBuild file
202         # should go in.
203         info_basedir = {}
204         for ci in self.component_infos:
205             # Ignore the $ROOT component.
206             if ci.parent is None:
207                 continue
208
209             info_basedir[ci.subpath] = info_basedir.get(ci.subpath, []) + [ci]
210
211         # Compute the list of subdirectories to scan.
212         subpath_subdirs = {}
213         for ci in self.component_infos:
214             # Ignore root components.
215             if ci.subpath == '/':
216                 continue
217
218             # Otherwise, append this subpath to the parent list.
219             parent_path = os.path.dirname(ci.subpath)
220             subpath_subdirs[parent_path] = parent_list = subpath_subdirs.get(
221                 parent_path, set())
222             parent_list.add(os.path.basename(ci.subpath))
223
224         # Generate the build files.
225         for subpath, infos in info_basedir.items():
226             # Order the components by name to have a canonical ordering.
227             infos.sort(key = lambda ci: ci.name)
228
229             # Format the components into llvmbuild fragments.
230             fragments = []
231
232             # Add the common fragments.
233             subdirectories = subpath_subdirs.get(subpath)
234             if subdirectories:
235                 fragment = """\
236 subdirectories = %s
237 """ % (" ".join(sorted(subdirectories)),)
238                 fragments.append(("common", fragment))
239
240             # Add the component fragments.
241             num_common_fragments = len(fragments)
242             for ci in infos:
243                 fragment = ci.get_llvmbuild_fragment()
244                 if fragment is None:
245                     continue
246
247                 name = "component_%d" % (len(fragments) - num_common_fragments)
248                 fragments.append((name, fragment))
249
250             if not fragments:
251                 continue
252
253             assert subpath.startswith('/')
254             directory_path = os.path.join(output_path, subpath[1:])
255
256             # Create the directory if it does not already exist.
257             if not os.path.exists(directory_path):
258                 os.makedirs(directory_path)
259
260             # In an effort to preserve comments (which aren't parsed), read in
261             # the original file and extract the comments. We only know how to
262             # associate comments that prefix a section name.
263             f = open(infos[0]._source_path)
264             comments_map = {}
265             comment_block = ""
266             for ln in f:
267                 if ln.startswith(';'):
268                     comment_block += ln
269                 elif ln.startswith('[') and ln.endswith(']\n'):
270                     comments_map[ln[1:-2]] = comment_block
271                 else:
272                     comment_block = ""
273             f.close()
274
275             # Create the LLVMBuild fil[e.
276             file_path = os.path.join(directory_path, 'LLVMBuild.txt')
277             f = open(file_path, "w")
278
279             # Write the header.
280             header_fmt = ';===- %s %s-*- Conf -*--===;'
281             header_name = '.' + os.path.join(subpath, 'LLVMBuild.txt')
282             header_pad = '-' * (80 - len(header_fmt % (header_name, '')))
283             header_string = header_fmt % (header_name, header_pad)
284             print >>f, """\
285 %s
286 ;
287 ;                     The LLVM Compiler Infrastructure
288 ;
289 ; This file is distributed under the University of Illinois Open Source
290 ; License. See LICENSE.TXT for details.
291 ;
292 ;===------------------------------------------------------------------------===;
293 ;
294 ; This is an LLVMBuild description file for the components in this subdirectory.
295 ;
296 ; For more information on the LLVMBuild system, please see:
297 ;
298 ;   http://llvm.org/docs/LLVMBuild.html
299 ;
300 ;===------------------------------------------------------------------------===;
301 """ % header_string
302
303             # Write out each fragment.each component fragment.
304             for name,fragment in fragments:
305                 comment = comments_map.get(name)
306                 if comment is not None:
307                     f.write(comment)
308                 print >>f, "[%s]" % name
309                 f.write(fragment)
310                 if fragment is not fragments[-1][1]:
311                     print >>f
312
313             f.close()
314
315     def write_library_table(self, output_path, enabled_optional_components):
316         # Write out the mapping from component names to required libraries.
317         #
318         # We do this in topological order so that we know we can append the
319         # dependencies for added library groups.
320         entries = {}
321         for c in self.ordered_component_infos:
322             # Skip optional components which are not enabled
323             if c.type_name == 'OptionalLibrary' \
324                 and c.name not in enabled_optional_components:
325                 continue
326
327             # Only certain components are in the table.
328             if c.type_name not in ('Library', 'OptionalLibrary', \
329                                    'LibraryGroup', 'TargetGroup'):
330                 continue
331
332             # Compute the llvm-config "component name". For historical reasons,
333             # this is lowercased based on the library name.
334             llvmconfig_component_name = c.get_llvmconfig_component_name()
335             
336             # Get the library name, or None for LibraryGroups.
337             if c.type_name == 'Library' or c.type_name == 'OptionalLibrary':
338                 library_name = c.get_prefixed_library_name()
339             else:
340                 library_name = None
341
342             # Get the component names of all the required libraries.
343             required_llvmconfig_component_names = [
344                 self.component_info_map[dep].get_llvmconfig_component_name()
345                 for dep in c.required_libraries]
346
347             # Insert the entries for library groups we should add to.
348             for dep in c.add_to_library_groups:
349                 entries[dep][2].append(llvmconfig_component_name)
350
351             # Add the entry.
352             entries[c.name] = (llvmconfig_component_name, library_name,
353                                required_llvmconfig_component_names)
354
355         # Convert to a list of entries and sort by name.
356         entries = entries.values()
357
358         # Create an 'all' pseudo component. We keep the dependency list small by
359         # only listing entries that have no other dependents.
360         root_entries = set(e[0] for e in entries)
361         for _,_,deps in entries:
362             root_entries -= set(deps)
363         entries.append(('all', None, root_entries))
364
365         entries.sort()
366
367         # Compute the maximum number of required libraries, plus one so there is
368         # always a sentinel.
369         max_required_libraries = max(len(deps)
370                                      for _,_,deps in entries) + 1
371
372         # Write out the library table.
373         make_install_dir(os.path.dirname(output_path))
374         f = open(output_path, 'w')
375         print >>f, """\
376 //===- llvm-build generated file --------------------------------*- C++ -*-===//
377 //
378 // Component Library Depenedency Table
379 //
380 // Automatically generated file, do not edit!
381 //
382 //===----------------------------------------------------------------------===//
383 """
384         print >>f, 'struct AvailableComponent {'
385         print >>f, '  /// The name of the component.'
386         print >>f, '  const char *Name;'
387         print >>f, ''
388         print >>f, '  /// The name of the library for this component (or NULL).'
389         print >>f, '  const char *Library;'
390         print >>f, ''
391         print >>f, '\
392   /// The list of libraries required when linking this component.'
393         print >>f, '  const char *RequiredLibraries[%d];' % (
394             max_required_libraries)
395         print >>f, '} AvailableComponents[%d] = {' % len(entries)
396         for name,library_name,required_names in entries:
397             if library_name is None:
398                 library_name_as_cstr = '0'
399             else:
400                 library_name_as_cstr = '"lib%s.a"' % library_name
401             print >>f, '  { "%s", %s, { %s } },' % (
402                 name, library_name_as_cstr,
403                 ', '.join('"%s"' % dep
404                           for dep in required_names))
405         print >>f, '};'
406         f.close()
407
408     def get_required_libraries_for_component(self, ci, traverse_groups = False):
409         """
410         get_required_libraries_for_component(component_info) -> iter
411
412         Given a Library component info descriptor, return an iterator over all
413         of the directly required libraries for linking with this component. If
414         traverse_groups is True, then library and target groups will be
415         traversed to include their required libraries.
416         """
417
418         assert ci.type_name in ('Library', 'LibraryGroup', 'TargetGroup')
419
420         for name in ci.required_libraries:
421             # Get the dependency info.
422             dep = self.component_info_map[name]
423
424             # If it is a library, yield it.
425             if dep.type_name == 'Library':
426                 yield dep
427                 continue
428
429             # Otherwise if it is a group, yield or traverse depending on what
430             # was requested.
431             if dep.type_name in ('LibraryGroup', 'TargetGroup'):
432                 if not traverse_groups:
433                     yield dep
434                     continue
435
436                 for res in self.get_required_libraries_for_component(dep, True):
437                     yield res
438
439     def get_fragment_dependencies(self):
440         """
441         get_fragment_dependencies() -> iter
442
443         Compute the list of files (as absolute paths) on which the output
444         fragments depend (i.e., files for which a modification should trigger a
445         rebuild of the fragment).
446         """
447
448         # Construct a list of all the dependencies of the Makefile fragment
449         # itself. These include all the LLVMBuild files themselves, as well as
450         # all of our own sources.
451         #
452         # Many components may come from the same file, so we make sure to unique
453         # these.
454         build_paths = set()
455         for ci in self.component_infos:
456             p = os.path.join(self.source_root, ci.subpath[1:], 'LLVMBuild.txt')
457             if p not in build_paths:
458                 yield p
459                 build_paths.add(p)
460
461         # Gather the list of necessary sources by just finding all loaded
462         # modules that are inside the LLVM source tree.
463         for module in sys.modules.values():
464             # Find the module path.
465             if not hasattr(module, '__file__'):
466                 continue
467             path = getattr(module, '__file__')
468             if not path:
469                 continue
470
471             # Strip off any compiled suffix.
472             if os.path.splitext(path)[1] in ['.pyc', '.pyo', '.pyd']:
473                 path = path[:-1]
474
475             # If the path exists and is in the source tree, consider it a
476             # dependency.
477             if (path.startswith(self.source_root) and os.path.exists(path)):
478                 yield path
479
480     def write_cmake_fragment(self, output_path):
481         """
482         write_cmake_fragment(output_path) -> None
483
484         Generate a CMake fragment which includes all of the collated LLVMBuild
485         information in a format that is easily digestible by a CMake. The exact
486         contents of this are closely tied to how the CMake configuration
487         integrates LLVMBuild, see CMakeLists.txt in the top-level.
488         """
489
490         dependencies = list(self.get_fragment_dependencies())
491
492         # Write out the CMake fragment.
493         make_install_dir(os.path.dirname(output_path))
494         f = open(output_path, 'w')
495
496         # Write the header.
497         header_fmt = '\
498 #===-- %s - LLVMBuild Configuration for LLVM %s-*- CMake -*--===#'
499         header_name = os.path.basename(output_path)
500         header_pad = '-' * (80 - len(header_fmt % (header_name, '')))
501         header_string = header_fmt % (header_name, header_pad)
502         print >>f, """\
503 %s
504 #
505 #                     The LLVM Compiler Infrastructure
506 #
507 # This file is distributed under the University of Illinois Open Source
508 # License. See LICENSE.TXT for details.
509 #
510 #===------------------------------------------------------------------------===#
511 #
512 # This file contains the LLVMBuild project information in a format easily
513 # consumed by the CMake based build system.
514 #
515 # This file is autogenerated by llvm-build, do not edit!
516 #
517 #===------------------------------------------------------------------------===#
518 """ % header_string
519
520         # Write the dependency information in the best way we can.
521         print >>f, """
522 # LLVMBuild CMake fragment dependencies.
523 #
524 # CMake has no builtin way to declare that the configuration depends on
525 # a particular file. However, a side effect of configure_file is to add
526 # said input file to CMake's internal dependency list. So, we use that
527 # and a dummy output file to communicate the dependency information to
528 # CMake.
529 #
530 # FIXME: File a CMake RFE to get a properly supported version of this
531 # feature."""
532         for dep in dependencies:
533             print >>f, """\
534 configure_file(\"%s\"
535                ${CMAKE_CURRENT_BINARY_DIR}/DummyConfigureOutput)""" % (
536                 cmake_quote_path(dep),)
537
538         # Write the properties we use to encode the required library dependency
539         # information in a form CMake can easily use directly.
540         print >>f, """
541 # Explicit library dependency information.
542 #
543 # The following property assignments effectively create a map from component
544 # names to required libraries, in a way that is easily accessed from CMake."""
545         for ci in self.ordered_component_infos:
546             # We only write the information for libraries currently.
547             if ci.type_name != 'Library':
548                 continue
549
550             print >>f, """\
551 set_property(GLOBAL PROPERTY LLVMBUILD_LIB_DEPS_%s %s)""" % (
552                 ci.get_prefixed_library_name(), " ".join(sorted(
553                      dep.get_prefixed_library_name()
554                      for dep in self.get_required_libraries_for_component(ci))))
555
556         f.close()
557
558     def write_make_fragment(self, output_path):
559         """
560         write_make_fragment(output_path) -> None
561
562         Generate a Makefile fragment which includes all of the collated
563         LLVMBuild information in a format that is easily digestible by a
564         Makefile. The exact contents of this are closely tied to how the LLVM
565         Makefiles integrate LLVMBuild, see Makefile.rules in the top-level.
566         """
567
568         dependencies = list(self.get_fragment_dependencies())
569
570         # Write out the Makefile fragment.
571         make_install_dir(os.path.dirname(output_path))
572         f = open(output_path, 'w')
573
574         # Write the header.
575         header_fmt = '\
576 #===-- %s - LLVMBuild Configuration for LLVM %s-*- Makefile -*--===#'
577         header_name = os.path.basename(output_path)
578         header_pad = '-' * (80 - len(header_fmt % (header_name, '')))
579         header_string = header_fmt % (header_name, header_pad)
580         print >>f, """\
581 %s
582 #
583 #                     The LLVM Compiler Infrastructure
584 #
585 # This file is distributed under the University of Illinois Open Source
586 # License. See LICENSE.TXT for details.
587 #
588 #===------------------------------------------------------------------------===#
589 #
590 # This file contains the LLVMBuild project information in a format easily
591 # consumed by the Makefile based build system.
592 #
593 # This file is autogenerated by llvm-build, do not edit!
594 #
595 #===------------------------------------------------------------------------===#
596 """ % header_string
597
598         # Write the dependencies for the fragment.
599         #
600         # FIXME: Technically, we need to properly quote for Make here.
601         print >>f, """\
602 # Clients must explicitly enable LLVMBUILD_INCLUDE_DEPENDENCIES to get
603 # these dependencies. This is a compromise to help improve the
604 # performance of recursive Make systems.""" 
605         print >>f, 'ifeq ($(LLVMBUILD_INCLUDE_DEPENDENCIES),1)'
606         print >>f, "# The dependencies for this Makefile fragment itself."
607         print >>f, "%s: \\" % (mk_quote_string_for_target(output_path),)
608         for dep in dependencies:
609             print >>f, "\t%s \\" % (dep,)
610         print >>f
611
612         # Generate dummy rules for each of the dependencies, so that things
613         # continue to work correctly if any of those files are moved or removed.
614         print >>f, """\
615 # The dummy targets to allow proper regeneration even when files are moved or
616 # removed."""
617         for dep in dependencies:
618             print >>f, "%s:" % (mk_quote_string_for_target(dep),)
619         print >>f, 'endif'
620
621         f.close()
622
623 def add_magic_target_components(parser, project, opts):
624     """add_magic_target_components(project, opts) -> None
625
626     Add the "magic" target based components to the project, which can only be
627     determined based on the target configuration options.
628
629     This currently is responsible for populating the required_libraries list of
630     the "all-targets", "Native", "NativeCodeGen", and "Engine" components.
631     """
632
633     # Determine the available targets.
634     available_targets = dict((ci.name,ci)
635                              for ci in project.component_infos
636                              if ci.type_name == 'TargetGroup')
637
638     # Find the configured native target.
639
640     # We handle a few special cases of target names here for historical
641     # reasons, as these are the names configure currently comes up with.
642     native_target_name = { 'x86' : 'X86',
643                            'x86_64' : 'X86',
644                            'Unknown' : None }.get(opts.native_target,
645                                                   opts.native_target)
646     if native_target_name is None:
647         native_target = None
648     else:
649         native_target = available_targets.get(native_target_name)
650         if native_target is None:
651             parser.error("invalid native target: %r (not in project)" % (
652                     opts.native_target,))
653         if native_target.type_name != 'TargetGroup':
654             parser.error("invalid native target: %r (not a target)" % (
655                     opts.native_target,))
656
657     # Find the list of targets to enable.
658     if opts.enable_targets is None:
659         enable_targets = available_targets.values()
660     else:
661         # We support both space separated and semi-colon separated lists.
662         if ' ' in opts.enable_targets:
663             enable_target_names = opts.enable_targets.split()
664         else:
665             enable_target_names = opts.enable_targets.split(';')
666
667         enable_targets = []
668         for name in enable_target_names:
669             target = available_targets.get(name)
670             if target is None:
671                 parser.error("invalid target to enable: %r (not in project)" % (
672                         name,))
673             if target.type_name != 'TargetGroup':
674                 parser.error("invalid target to enable: %r (not a target)" % (
675                         name,))
676             enable_targets.append(target)
677
678     # Find the special library groups we are going to populate. We enforce that
679     # these appear in the project (instead of just adding them) so that they at
680     # least have an explicit representation in the project LLVMBuild files (and
681     # comments explaining how they are populated).
682     def find_special_group(name):
683         info = info_map.get(name)
684         if info is None:
685             fatal("expected project to contain special %r component" % (
686                     name,))
687
688         if info.type_name != 'LibraryGroup':
689             fatal("special component %r should be a LibraryGroup" % (
690                     name,))
691
692         if info.required_libraries:
693             fatal("special component %r must have empty %r list" % (
694                     name, 'required_libraries'))
695         if info.add_to_library_groups:
696             fatal("special component %r must have empty %r list" % (
697                     name, 'add_to_library_groups'))
698
699         info._is_special_group = True
700         return info
701
702     info_map = dict((ci.name, ci) for ci in project.component_infos)
703     all_targets = find_special_group('all-targets')
704     native_group = find_special_group('Native')
705     native_codegen_group = find_special_group('NativeCodeGen')
706     engine_group = find_special_group('Engine')
707
708     # Set the enabled bit in all the target groups, and append to the
709     # all-targets list.
710     for ci in enable_targets:
711         all_targets.required_libraries.append(ci.name)
712         ci.enabled = True
713
714     # If we have a native target, then that defines the native and
715     # native_codegen libraries.
716     if native_target and native_target.enabled:
717         native_group.required_libraries.append(native_target.name)
718         native_codegen_group.required_libraries.append(
719             '%sCodeGen' % native_target.name)
720
721     # If we have a native target with a JIT, use that for the engine. Otherwise,
722     # use the interpreter.
723     if native_target and native_target.enabled and native_target.has_jit:
724         engine_group.required_libraries.append('JIT')
725         engine_group.required_libraries.append(native_group.name)
726     else:
727         engine_group.required_libraries.append('Interpreter')
728
729 def main():
730     from optparse import OptionParser, OptionGroup
731     parser = OptionParser("usage: %prog [options]")
732
733     group = OptionGroup(parser, "Input Options")
734     group.add_option("", "--source-root", dest="source_root", metavar="PATH",
735                       help="Path to the LLVM source (inferred if not given)",
736                       action="store", default=None)
737     group.add_option("", "--llvmbuild-source-root",
738                      dest="llvmbuild_source_root",
739                      help=(
740             "If given, an alternate path to search for LLVMBuild.txt files"),
741                      action="store", default=None, metavar="PATH")
742     group.add_option("", "--build-root", dest="build_root", metavar="PATH",
743                       help="Path to the build directory (if needed) [%default]",
744                       action="store", default=None)
745     parser.add_option_group(group)
746
747     group = OptionGroup(parser, "Output Options")
748     group.add_option("", "--print-tree", dest="print_tree",
749                      help="Print out the project component tree [%default]",
750                      action="store_true", default=False)
751     group.add_option("", "--write-llvmbuild", dest="write_llvmbuild",
752                       help="Write out the LLVMBuild.txt files to PATH",
753                       action="store", default=None, metavar="PATH")
754     group.add_option("", "--write-library-table",
755                      dest="write_library_table", metavar="PATH",
756                      help="Write the C++ library dependency table to PATH",
757                      action="store", default=None)
758     group.add_option("", "--write-cmake-fragment",
759                      dest="write_cmake_fragment", metavar="PATH",
760                      help="Write the CMake project information to PATH",
761                      action="store", default=None)
762     group.add_option("", "--write-make-fragment",
763                       dest="write_make_fragment", metavar="PATH",
764                      help="Write the Makefile project information to PATH",
765                      action="store", default=None)
766     group.add_option("", "--configure-target-def-file",
767                      dest="configure_target_def_files",
768                      help="""Configure the given file at SUBPATH (relative to
769 the inferred or given source root, and with a '.in' suffix) by replacing certain
770 substitution variables with lists of targets that support certain features (for
771 example, targets with AsmPrinters) and write the result to the build root (as
772 given by --build-root) at the same SUBPATH""",
773                      metavar="SUBPATH", action="append", default=None)
774     parser.add_option_group(group)
775
776     group = OptionGroup(parser, "Configuration Options")
777     group.add_option("", "--native-target",
778                       dest="native_target", metavar="NAME",
779                       help=("Treat the named target as the 'native' one, if "
780                             "given [%default]"),
781                       action="store", default=None)
782     group.add_option("", "--enable-targets",
783                       dest="enable_targets", metavar="NAMES",
784                       help=("Enable the given space or semi-colon separated "
785                             "list of targets, or all targets if not present"),
786                       action="store", default=None)
787     group.add_option("", "--enable-optional-components",
788                       dest="optional_components", metavar="NAMES",
789                       help=("Enable the given space or semi-colon separated "
790                             "list of optional components"),
791                       action="store", default=None)
792     parser.add_option_group(group)
793
794     (opts, args) = parser.parse_args()
795
796     # Determine the LLVM source path, if not given.
797     source_root = opts.source_root
798     if source_root:
799         if not os.path.exists(os.path.join(source_root, 'lib', 'VMCore',
800                                            'Function.cpp')):
801             parser.error('invalid LLVM source root: %r' % source_root)
802     else:
803         llvmbuild_path = os.path.dirname(__file__)
804         llvm_build_path = os.path.dirname(llvmbuild_path)
805         utils_path = os.path.dirname(llvm_build_path)
806         source_root = os.path.dirname(utils_path)
807         if not os.path.exists(os.path.join(source_root, 'lib', 'VMCore',
808                                            'Function.cpp')):
809             parser.error('unable to infer LLVM source root, please specify')
810
811     # Construct the LLVM project information.
812     llvmbuild_source_root = opts.llvmbuild_source_root or source_root
813     project_info = LLVMProjectInfo.load_from_path(
814         source_root, llvmbuild_source_root)
815
816     # Add the magic target based components.
817     add_magic_target_components(parser, project_info, opts)
818
819     # Validate the project component info.
820     project_info.validate_components()
821
822     # Print the component tree, if requested.
823     if opts.print_tree:
824         project_info.print_tree()
825
826     # Write out the components, if requested. This is useful for auto-upgrading
827     # the schema.
828     if opts.write_llvmbuild:
829         project_info.write_components(opts.write_llvmbuild)
830
831     # Write out the required library table, if requested.
832     if opts.write_library_table:
833         project_info.write_library_table(opts.write_library_table,
834                                          opts.optional_components)
835
836     # Write out the make fragment, if requested.
837     if opts.write_make_fragment:
838         project_info.write_make_fragment(opts.write_make_fragment)
839
840     # Write out the cmake fragment, if requested.
841     if opts.write_cmake_fragment:
842         project_info.write_cmake_fragment(opts.write_cmake_fragment)
843
844     # Configure target definition files, if requested.
845     if opts.configure_target_def_files:
846         # Verify we were given a build root.
847         if not opts.build_root:
848             parser.error("must specify --build-root when using "
849                          "--configure-target-def-file")
850
851         # Create the substitution list.
852         available_targets = [ci for ci in project_info.component_infos
853                              if ci.type_name == 'TargetGroup']
854         substitutions = [
855             ("@LLVM_ENUM_TARGETS@",
856              ' '.join('LLVM_TARGET(%s)' % ci.name
857                       for ci in available_targets)),
858             ("@LLVM_ENUM_ASM_PRINTERS@",
859              ' '.join('LLVM_ASM_PRINTER(%s)' % ci.name
860                       for ci in available_targets
861                       if ci.has_asmprinter)),
862             ("@LLVM_ENUM_ASM_PARSERS@",
863              ' '.join('LLVM_ASM_PARSER(%s)' % ci.name
864                       for ci in available_targets
865                       if ci.has_asmparser)),
866             ("@LLVM_ENUM_DISASSEMBLERS@",
867              ' '.join('LLVM_DISASSEMBLER(%s)' % ci.name
868                       for ci in available_targets
869                       if ci.has_disassembler))]
870
871         # Configure the given files.
872         for subpath in opts.configure_target_def_files:
873             inpath = os.path.join(source_root, subpath + '.in')
874             outpath = os.path.join(opts.build_root, subpath)
875             result = configutil.configure_file(inpath, outpath, substitutions)
876             if not result:
877                 note("configured file %r hasn't changed" % outpath)
878
879 if __name__=='__main__':
880     main()